Quantcast
Channel: CodeChef Discuss - latest questions
Viewing all articles
Browse latest Browse all 39796

Time complexity of vector's element deletion.

$
0
0

Hey guys! I was trying out a question on vector, and am stuck on this concept.

Suppose i write this code-

for(i=0;i< vec.size();i++)
{
   if(vec[i]==5)
   {
       vec.erase (vec.begin()+i);//Statement 1. Erasing element at index i.
   }
}

Suppose that number of elements, N, is ~10^6, and it is the worst case (i.e. every element is 5 and has to be deleted). With reference to above (and any other necessary assumption needed), please tell-

  1. The element i will get if a use "cout<< vec[i]" after statement 1. Meaning, if the vector is [1,2,5,3,4], and now 5 is deleted. So printing "vec[i]" would give me 2 or 3? (i feel it would be 3 but not sure)
  2. Time complexity of above. I searched and found that vec.erase(vec.begin() , vec.end() ) has a linear time complexity, but is it true even for cases when only 1 element is to be deleted? Or is it O(1) for such a case? In other words, i want to ask if the overall time complexity of the code segment in question (in worst case) is O(N) or O(N^2)?

Viewing all articles
Browse latest Browse all 39796

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>