Sobes.tech
Junior — Middle

What is the time complexity of deleting an element in a vector container?

sobes.tech AI

Answer from AI

In the C++ standard library, the operation of removing an element from a std::vector (for example, using erase) has a worst-case time complexity of O(n), where n is the number of elements in the vector.

This is because, after removing an element, all subsequent elements are shifted to fill the gap, which requires copying or moving elements.

Example:

std::vector<int> v = {1, 2, 3, 4, 5};
v.erase(v.begin() + 2); // removes the element '3'
// elements '4' and '5' shift left by one position

Thus, deleting an element in the middle or at the beginning of a vector is a linear-time operation.