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?"
Practice
fold and reduce in Kotlin?Solution
Step 1: Understand
foldbehaviorfoldrequires an initial value and then applies the operation starting from that value.Step 2: Understand
reducebehaviorreduceuses the first element of the list as the initial value and then applies the operation to the rest.Final Answer:
foldstarts with an initial value;reducestarts with the first list item. -> Option AQuick Check:
fold initial value vs reduce first item = C [OK]
- Thinking fold modifies the original list
- Assuming reduce needs an initial value
- Believing fold only works on numbers
fold on a list listOf(1, 2, 3) to sum all elements starting from 10?Solution
Step 1: Check fold function signature
foldtakes an initial value and a lambda with two parameters: accumulator and current item.Step 2: Match syntax with options
listOf(1, 2, 3).fold(10) { acc, item -> acc + item } correctly usesfold(10) { acc, item -> acc + item }. Others miss initial value or have wrong lambda syntax.Final Answer:
listOf(1, 2, 3).fold(10) { acc, item -> acc + item } -> Option CQuick Check:
fold(initial) with lambda = D [OK]
- Omitting the initial value in fold
- Using incorrect lambda syntax
- Passing expression instead of lambda
val numbers = listOf(2, 3, 4)
val result = numbers.reduce { acc, item -> acc * item }
println(result)Solution
Step 1: Understand reduce operation
reducestarts with first element (2) as accumulator, then multiplies by next items.Step 2: Calculate step-by-step
2 * 3 = 6, then 6 * 4 = 24.Final Answer:
24 -> Option DQuick Check:
2 * 3 * 4 = 24 [OK]
- Adding instead of multiplying
- Starting from zero instead of first item
- Expecting a list output
reduce:val emptyList = listOf<Int>()
val result = emptyList.reduce { acc, item -> acc + item }
println(result)Solution
Step 1: Check reduce behavior on empty list
reducerequires at least one element; empty list causes runtime exception.Step 2: Understand exception cause
Since list is empty, no first element exists to start reduction, so it throwsNoSuchElementException.Final Answer:
Throws exception because list is empty -> Option AQuick Check:
reduce on empty list = Exception [OK]
- Assuming reduce returns 0 on empty list
- Thinking lambda syntax is wrong
- Expecting null instead of exception
listOf("a", "b", "c"), which Kotlin expression using fold produces the string "abc-"?Solution
Step 1: Understand fold with initial empty string
Starting with empty string, each item is appended with a dash after it.Step 2: Check each step of fold
"" + "a" + "-" = "a-"; then "a-" + "b" + "-" = "a-b-"; then "a-b-" + "c" + "-" = "abc-".Final Answer:
listOf("a", "b", "c").fold("") { acc, s -> acc + s + "-" } -> Option BQuick Check:
fold with empty start and append = A [OK]
- Using reduce which starts with first item, missing initial empty string
- Appending dash before instead of after
- Wrong initial value causing different output
Ready to prove it?
Pass the test and this pattern moves unknown
