Junior
What is the algorithmic complexity of adding elements to the end of an array?
sobes.tech AI
Answer from AI
O(1) amortized.
When adding an element to the end of an array, if there is free space, a simple assignment occurs, which takes O(1).
If the array is full, memory reallocation and copying all existing elements to a new, larger storage is required. This operation takes O(N), where N is the number of elements in the array.
Thanks to the doubling strategy during reallocation, the average cost of adding an element over many operations tends to a constant.
Example in Swift:
var array = [Int]()
// Adding, most likely O(1)
array.append(1)
// May require memory reallocation and become O(N)
// But the amortized cost for the entire append sequence remains O(1)
array.append(2)