Array creation and type inference in Swift - Time & Space Complexity
When we create arrays in Swift, the time it takes depends on how many items we add. Understanding this helps us know how fast our program runs as we add more data.
We want to find out how the time to create an array grows when we add more elements.
Analyze the time complexity of the following code snippet.
var numbers = [Int]()
for i in 1...n {
numbers.append(i)
}
This code creates an empty array and adds numbers from 1 to n one by one.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Adding an element to the array using
append. - How many times: Exactly n times, once for each number from 1 to n.
Each time we add a number, the program does a small task. So if we add 10 numbers, it does about 10 tasks; for 100 numbers, about 100 tasks; and for 1000 numbers, about 1000 tasks.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 |
| 100 | 100 |
| 1000 | 1000 |
Pattern observation: The number of operations grows directly with the number of items added.
Time Complexity: O(n)
This means the time to create the array grows in a straight line as we add more items.
[X] Wrong: "Appending to an array always takes the same fixed time, no matter how big the array is."
[OK] Correct: Sometimes, Swift needs to allocate a bigger space for the array, which takes extra time. But this happens only occasionally, so on average, appending is still fast.
Knowing how array creation time grows helps you explain how your code handles data. It shows you understand how programs work with memory and speed, which is a useful skill in many coding tasks.
"What if we create the array with a fixed size upfront instead of appending? How would the time complexity change?"