Junior — Middle
Kui suur on operatsiooni lisada element massiivi alguses ajakulu?
sobes.tech AI
Vastus AI-lt
Adding an element to the beginning of an array usually has a time complexity of O(n), where n is the number of elements in the array.
This is because, to insert at the beginning, all existing elements need to be shifted to the right to make space for the new element. In dynamic arrays (e.g., Swift Array), this process requires copying or shifting elements, which takes time proportional to the number of elements.
Example:
var array = [2, 3, 4]
array.insert(1, at: 0) // insert 1 at the beginning
print(array) // [1, 2, 3, 4]
Here, when inserting 1, all elements are shifted one position to the right.