Reduce method in Javascript - Time & Space Complexity
We want to see how the time to run the reduce method changes as the list gets bigger.
How does the number of steps grow when we use reduce on an array?
Analyze the time complexity of the following code snippet.
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((total, num) => total + num, 0);
console.log(sum);
This code adds all numbers in the array to get their total sum.
- Primary operation: The reduce method visits each item in the array once.
- How many times: It runs the function once for every element in the array.
As the array gets bigger, the number of steps grows in a straight line with the number of items.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 steps |
| 100 | 100 steps |
| 1000 | 1000 steps |
Pattern observation: Doubling the input doubles the work done.
Time Complexity: O(n)
This means the time to finish grows directly with the number of items in the array.
[X] Wrong: "Reduce runs faster than a simple loop because it's a special method."
[OK] Correct: Reduce still looks at every item once, just like a loop, so it takes about the same time.
Knowing how reduce works helps you explain your code clearly and shows you understand how loops affect speed.
"What if we used reduce on an array of arrays, combining them? How would the time complexity change?"