Junior — Middle
What is the worst-case time complexity of the operation of removing elements from a vector?
sobes.tech AI
Answer from AI
In the worst case, removing elements from a vector (std::vector in C++) has a time complexity of O(n), where n is the number of elements in the vector after the removal position. This is because, after removing elements, all subsequent elements need to be shifted to the left to fill the gap.
For example, if you remove an element at the beginning of the vector, all other elements need to be shifted one position forward, which requires O(n) operations.
std::vector<int> v = {1, 2, 3, 4, 5};
v.erase(v.begin()); // remove the first element
// all elements are shifted one position to the left
If an element at the end is removed, no shifting is required, and the operation is closer to O(1). But in the worst case — O(n).