Sobes.tech
Junior — Middle

What is the time complexity of adding an element to the beginning of an array?

sobes.tech AI

Answer from AI

Adding an element to the beginning of an array typically has a time complexity of O(n), where n is the number of elements in the array.

This is because inserting at the beginning requires shifting all existing elements to the right to make space for the new element. In dynamic arrays (such as Swift Array), this process involves copying or shifting elements, which takes time proportional to the number of elements.

Example:

var array = [2, 3, 4]
array.insert(1, at: 0) // inserting 1 at the beginning
print(array) // [1, 2, 3, 4]

Here, when inserting 1, all elements are shifted one position to the right.