Collection slicing and indices in Swift - Time & Space Complexity
When working with collections in Swift, slicing lets us take parts of the collection. Understanding how long slicing takes helps us write faster code.
We want to know: how does the time to slice grow as the collection gets bigger?
Analyze the time complexity of the following code snippet.
let numbers = Array(1...1000)
let slice = numbers[100..<200]
for number in slice {
print(number)
}
This code creates an array of numbers, takes a slice from index 100 to 199, then prints each number in the slice.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the slice to print each number.
- How many times: The loop runs once for each element in the slice (100 times here).
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 |
| 100 | 100 |
| 1000 | 1000 |
Pattern observation: The number of operations grows directly with the slice size. Double the slice size, double the work.
Time Complexity: O(n)
This means the time to process the slice grows linearly with the number of elements in the slice.
[X] Wrong: "Slicing an array is instant and costs no time."
[OK] Correct: While slicing itself is fast, using the slice (like looping through it) takes time proportional to the slice size.
Knowing how slicing and indexing affect time helps you explain your code choices clearly and shows you understand how data size impacts performance.
"What if we changed the slice to a filter that picks elements based on a condition? How would the time complexity change?"