FlatMap for nested collections in Swift - Time & Space Complexity
When using flatMap on nested collections, it is important to understand how the work grows as the size of the collections increases.
We want to know how many steps the program takes as the input gets bigger.
Analyze the time complexity of the following code snippet.
let nestedArrays = [[1, 2], [3, 4, 5], [6]]
let flattened = nestedArrays.flatMap { innerArray in
innerArray.map { $0 * 2 }
}
print(flattened)
This code doubles each number inside nested arrays and then flattens them into a single array.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Traversing each inner array and mapping its elements.
- How many times: Once for each element inside every inner array.
As the total number of elements inside all inner arrays grows, the work grows proportionally.
| Input Size (total elements) | Approx. Operations |
|---|---|
| 10 | About 10 operations |
| 100 | About 100 operations |
| 1000 | About 1000 operations |
Pattern observation: The number of steps grows directly with the total number of elements.
Time Complexity: O(n)
This means the time to complete the operation grows in a straight line with the total number of elements inside all nested arrays.
[X] Wrong: "Because there are nested arrays, the time complexity must be quadratic or worse."
[OK] Correct: The operation visits each element only once, so the total work depends on the total number of elements, not the number of arrays squared.
Understanding how nested collections affect time helps you explain your code clearly and shows you can think about efficiency in real situations.
"What if the inner arrays were very large but the number of inner arrays was small? How would the time complexity change?"
Practice
flatMap function do when applied to a nested array in Swift?Solution
Step 1: Understand the purpose of flatMap
TheflatMapfunction is designed to take a collection of collections and combine them into one single collection by flattening the nested structure.Step 2: Identify the effect on nested arrays
When applied to nested arrays,flatMapmerges all inner arrays into one continuous array containing all elements.Final Answer:
It flattens the nested arrays into a single array by combining all elements. -> Option AQuick Check:
flatMap flattens nested arrays = A [OK]
- Thinking flatMap sorts the array
- Confusing flatMap with removing duplicates
- Assuming flatMap converts arrays to dictionaries
let nested = [[1, 2], [3, 4]] using flatMap in Swift?Solution
Step 1: Recall flatMap syntax
The correct syntax for flattening nested arrays usesflatMapwith a closure that returns each inner array:nested.flatMap { $0 }.Step 2: Evaluate each option
let flat = nested.flatMap { $0 } uses the correct closure syntax. let flat = nested.map { $0 } usesmapwhich does not flatten. let flat = nested.flatMap() is invalid syntax. let flat = nested.flatten() uses a non-existent methodflatten().Final Answer:
let flat = nested.flatMap { $0 } -> Option DQuick Check:
flatMap with closure { $0 } flattens nested arrays [OK]
- Using map instead of flatMap
- Calling flatMap without closure
- Using non-existent flatten() method
let nested = [[1, 2], [3, 4], [5]]
let result = nested.flatMap { $0.map { $0 * 2 } }
print(result)Solution
Step 1: Understand the inner map operation
Each inner array is mapped to a new array where each element is multiplied by 2, so [1,2] becomes [2,4], [3,4] becomes [6,8], and [5] becomes [10].Step 2: Apply flatMap to flatten the mapped arrays
TheflatMapthen flattens these arrays into a single array: [2, 4, 6, 8, 10].Final Answer:
[2, 4, 6, 8, 10] -> Option BQuick Check:
flatMap + map doubles and flattens = [2,4,6,8,10] [OK]
- Confusing flatMap with map output
- Expecting nested arrays instead of flattened
- Multiplying elements incorrectly
let nested = [["a", "b"], ["c"]] let flat = nested.flatMap() print(flat)
Solution
Step 1: Check flatMap usage
TheflatMapfunction requires a closure to specify how to flatten the nested arrays, such as{ $0 }. CallingflatMap()without arguments is invalid.Step 2: Verify other parts of the code
Arrays of strings can be flattened with flatMap, variables can be assigned with let, and print syntax is correct.Final Answer:
flatMap requires a closure to specify how to flatten the nested arrays. -> Option AQuick Check:
flatMap needs closure { $0 } to flatten [OK]
- Calling flatMap without closure
- Thinking flatMap can't flatten strings
- Misunderstanding let variable assignment
- Assuming print syntax is wrong
let nested: [[Int?]] = [[1, nil], [3, 4], [nil]], which Swift code using flatMap correctly produces a flat array of non-nil integers?Solution
Step 1: Understand the data and goal
The nested array contains optional integers, some are nil. The goal is to flatten and remove nil values, keeping only non-nil integers.Step 2: Analyze each option
let flat = nested.flatMap { $0.compactMap { $0 } } usescompactMapinsideflatMapto unwrap and remove nils, then flatten. let flat = nested.flatMap { $0.map { $0! } } force unwraps which can crash if nil exists. let flat = nested.flatMap { $0.filter { $0 != nil } } filters nil but keeps optionals, so result is nested optionals. let flat = nested.flatMap { $0 } just flattens but keeps nils.Final Answer:
let flat = nested.flatMap { $0.compactMap { $0 } } -> Option CQuick Check:
flatMap + compactMap unwraps and flattens non-nil values [OK]
- Force unwrapping optionals causing runtime errors
- Filtering nil but not unwrapping optionals
- Flattening without removing nil values
Ready to prove it?
Pass the test and this pattern moves unknown
