Map, filter, reduce patterns in Swift - Time & Space Complexity
When using map, filter, and reduce in Swift, it's important to know how the time to run grows as the input list gets bigger.
We want to see how many steps these patterns take when working on arrays.
Analyze the time complexity of the following code snippet.
let numbers = [1, 2, 3, 4, 5]
let doubled = numbers.map { $0 * 2 }
let evens = numbers.filter { $0 % 2 == 0 }
let sum = numbers.reduce(0) { $0 + $1 }
This code doubles each number, selects even numbers, and sums all numbers in the array.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Each pattern loops through the entire array once.
- How many times: Each element is visited exactly one time per pattern.
As the array gets bigger, the number of steps grows in a straight line with the number of elements.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 steps per pattern |
| 100 | About 100 steps per pattern |
| 1000 | About 1000 steps per pattern |
Pattern observation: The work grows evenly as the input size grows.
Time Complexity: O(n)
This means the time to finish grows directly with the number of items in the array.
[X] Wrong: "Using map, filter, and reduce together means the time is multiplied and becomes much slower."
[OK] Correct: Each pattern goes through the array once, so doing them one after another adds their times, but each is still just one pass through the data.
Understanding how these patterns scale helps you explain your code clearly and shows you know how to write efficient Swift code.
"What if we combined map and filter into one loop? How would the time complexity change?"