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?"
Practice
map function do in Swift when applied to an array?Solution
Step 1: Understand the purpose of map
Themapfunction applies a transformation to each element in the array, creating a new array with the changed items.Step 2: Compare with other functions
Unlikefilterwhich removes items, orreducewhich combines items,mapchanges each item individually.Final Answer:
It changes each item in the array based on a rule. -> Option AQuick Check:
map = change each item [OK]
- Confusing map with filter or reduce
- Thinking map removes items
- Assuming map combines items into one
filter on an array numbers to keep only even numbers?Solution
Step 1: Identify correct filter syntax
Thefiltermethod uses a closure with a condition inside curly braces, like{ $0 % 2 == 0 }, to keep items matching the condition.Step 2: Check each option
let evens = numbers.filter { $0 % 2 == 0 } correctly usesfilterwith the closure. let evens = numbers.map { $0 % 2 == 0 } usesmapwhich changes items, not filters. let evens = numbers.reduce(0) { $0 % 2 == 0 } misusesreduce. let evens = numbers.filter($0 % 2 == 0) misses the closure braces.Final Answer:
let evens = numbers.filter { $0 % 2 == 0 } -> Option DQuick Check:
filter syntax = filter { condition } [OK]
- Using map instead of filter
- Omitting braces in closure
- Using reduce incorrectly for filtering
let numbers = [1, 2, 3, 4]
let result = numbers.reduce(0) { $0 + $1 }
print(result)Solution
Step 1: Understand reduce with initial value 0
Thereducestarts with 0 and adds each number in the array: 0 + 1 + 2 + 3 + 4.Step 2: Calculate the sum
Adding all numbers: 0 + 1 = 1, 1 + 2 = 3, 3 + 3 = 6, 6 + 4 = 10.Final Answer:
10 -> Option CQuick Check:
Sum of [1,2,3,4] = 10 [OK]
- Confusing reduce with map or filter output
- Forgetting initial value in reduce
- Expecting array output instead of single value
let words = ["apple", "banana", "cherry"]
let filtered = words.filter { word in
word.count > 5
}
print(filtered)Solution
Step 1: Check filter closure syntax
The closure uses implicit return because it is a single expression, so no explicitreturnis needed.Step 2: Verify property usage
word.countis the correct way to get string length in Swift, so no error there.Final Answer:
No error, code runs correctly -> Option AQuick Check:
Single-expression closures return implicitly [OK]
- Adding unnecessary return keyword
- Confusing count with length property
- Thinking filter needs map syntax
map, filter, and reduce together to find the sum of squares of only the odd numbers?
Choose the correct Swift code.Solution
Step 1: Filter odd numbers first
We want only odd numbers, so usefilter { $0 % 2 != 0 }to keep them.Step 2: Map to square each odd number
Usemap { $0 * $0 }to get squares of the filtered odd numbers.Step 3: Reduce to sum all squares
Usereduce(0, +)to add all squared values into one sum.Final Answer:
let sum = numbers.filter { $0 % 2 != 0 }.map { $0 * $0 }.reduce(0, +) -> Option BQuick Check:
Filter odds, map squares, reduce sum [OK]
- Mapping before filtering odd numbers
- Filtering even numbers by mistake
- Using reduce without mapping squares
Ready to prove it?
Pass the test and this pattern moves unknown
