Junior — Middle
What is the time complexity of inserting an element at the beginning of an array?
sobes.tech AI
Answer from AI
Inserting an element at the beginning of an array is an operation with a time complexity of (O(n)), where (n) is the current size of the array.
The reason is that arrays are stored contiguously in memory, and to insert an element at the beginning, all existing elements need to be shifted one position to the right to make space for the new element. This shift requires copying all elements, which takes time proportional to the number of elements.
Example in Swift:
var array = [2, 3, 4]
array.insert(1, at: 0) // Insert 1 at the beginning
// After the operation, array = [1, 2, 3, 4]
Here, inserting at the beginning of the array causes the elements 2, 3, 4 to be shifted to the right.