Junior — Middle
What is the worst-case and average-case time complexity of inserting an element into a vector in C++?
sobes.tech AI
Answer from AI
In a dynamic array of type vector in C++, the insert operation has:
- Average time complexity O(1) — when there is free space in the allocated memory, the element is simply added to the end.
- Worst-case time complexity O(n) — when the allocated memory is full, a reallocation occurs: a new block of larger size is allocated, all existing elements are copied to the new block, and then the new element is added.
Thus, despite rare costly copy operations, the amortized complexity of insertion remains O(1).