Array operations (append, insert, remove) in Swift - Time & Space Complexity
When working with arrays, it's important to know how fast operations like adding or removing items happen.
We want to understand how the time to do these operations changes as the array grows.
Analyze the time complexity of these common array operations in Swift.
var numbers = [1, 2, 3, 4, 5]
numbers.append(6) // Add at the end
numbers.insert(0, at: 0) // Insert at the start
numbers.remove(at: 2) // Remove from middle
This code shows adding, inserting, and removing elements in an array.
Look at what happens inside each operation:
- Primary operation: Moving elements to make space or fill gaps.
- How many times: Depends on position: appending moves none, inserting/removing near start moves many.
As the array gets bigger, the cost changes differently for each operation.
| Input Size (n) | Append | Insert at start | Remove from middle |
|---|---|---|---|
| 10 | ~1 operation | ~10 operations | ~8 operations |
| 100 | ~1 operation | ~100 operations | ~50 operations |
| 1000 | ~1 operation | ~1000 operations | ~500 operations |
Pattern observation: Appending stays fast, but inserting or removing near the start or middle grows with array size.
Time Complexity: O(1) for append, O(n) for insert and remove
This means adding at the end is quick no matter the size, but inserting or removing inside takes longer as the array grows.
[X] Wrong: "All array operations take the same time regardless of position."
[OK] Correct: Because inserting or removing inside requires shifting many elements, which takes more time as the array grows.
Understanding these differences helps you explain why some operations are faster and shows you know how data structures work under the hood.
"What if we used a linked list instead of an array? How would the time complexity for insert and remove change?"