Junior — Middle
How is the time complexity of inserting an element at the end of an array determined?
sobes.tech AI
Answer from AI
Inserting an element at the end of an array in iOS depends on the array type:
-
For fixed-size arrays (e.g., C arrays), inserting at the end is impossible without creating a new array.
-
For NSMutableArray or Swift arrays, which dynamically resize, inserting at the end is usually performed in amortized O(1) time. This means that most of the time, adding is quick, but sometimes, when the array reaches its current capacity, a memory reallocation and copying of elements occur, which takes more time.
Example in Swift:
var array = [1, 2, 3]
array.append(4) // Usually O(1), sometimes O(n) during reallocation