Fold and reduce operations in Kotlin - Time & Space Complexity
We want to understand how the time to run fold and reduce operations changes as the input list grows.
How does the number of steps grow when we process more items?
Analyze the time complexity of the following code snippet.
val numbers = listOf(1, 2, 3, 4, 5)
val sum = numbers.fold(0) { acc, num -> acc + num }
val product = numbers.reduce { acc, num -> acc * num }
This code calculates the sum and product of all numbers in a list using fold and reduce.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The fold and reduce functions each loop through the entire list once.
- How many times: Each element in the list is visited exactly one time during the operation.
As the list gets bigger, the number of steps grows directly with the number of items.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 steps |
| 100 | About 100 steps |
| 1000 | About 1000 steps |
Pattern observation: The work grows in a straight line as the list size increases.
Time Complexity: O(n)
This means the time to complete fold or reduce grows directly with the number of items in the list.
[X] Wrong: "Fold and reduce run in constant time because they just combine values."
[OK] Correct: Even though they combine values simply, they must look at each item once, so time grows with list size.
Understanding how fold and reduce scale helps you explain how simple list operations behave with bigger data, a useful skill in many coding tasks.
"What if we used fold or reduce on a nested list (list of lists)? How would the time complexity change?"