Array iteration and enumerated in Swift - Time & Space Complexity
When we loop through an array using iteration and the enumerated method, we want to know how the time it takes grows as the array gets bigger.
We ask: How does the number of steps change when the array size increases?
Analyze the time complexity of the following code snippet.
let numbers = [10, 20, 30, 40, 50]
for (index, value) in numbers.enumerated() {
print("Index: \(index), Value: \(value)")
}
This code goes through each item in the array and prints its position and value.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each element of the array once.
- How many times: Exactly once for each element, so as many times as the array length.
As the array gets bigger, the number of steps grows directly with the number of items.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 steps |
| 100 | 100 steps |
| 1000 | 1000 steps |
Pattern observation: The steps increase evenly as the array size grows.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the number of items in the array.
[X] Wrong: "Using enumerated makes the loop slower because it adds extra work."
[OK] Correct: Enumerated just pairs each item with its index during the same single pass, so it does not add extra loops or slow down the process noticeably.
Understanding how simple loops grow with input size helps you explain your code clearly and shows you know how to think about efficiency in real projects.
"What if we nested another loop inside to compare each element with every other element? How would the time complexity change?"