0
0
Swiftprogramming~5 mins

Map, filter, reduce patterns in Swift - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Map, filter, reduce patterns
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

As the array gets bigger, the number of steps grows in a straight line with the number of elements.

Input Size (n)Approx. Operations
10About 10 steps per pattern
100About 100 steps per pattern
1000About 1000 steps per pattern

Pattern observation: The work grows evenly as the input size grows.

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows directly with the number of items in the array.

Common Mistake

[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.

Interview Connect

Understanding how these patterns scale helps you explain your code clearly and shows you know how to write efficient Swift code.

Self-Check

"What if we combined map and filter into one loop? How would the time complexity change?"