Challenge - 5 Problems
Fold and Reduce Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this fold operation?
Consider the following Kotlin code using
fold. What will be printed?Kotlin
val numbers = listOf(1, 2, 3, 4) val result = numbers.fold(10) { acc, num -> acc - num } println(result)
Attempts:
2 left
💡 Hint
Remember that fold starts with the initial value and applies the operation from left to right.
✗ Incorrect
The fold starts with 10. Then 10 - 1 = 9, 9 - 2 = 7, 7 - 3 = 4, 4 - 4 = 0. The output is 0.
❓ Predict Output
intermediate2:00remaining
What is the output of this reduce operation?
Look at this Kotlin code using
reduce. What will it print?Kotlin
val numbers = listOf(2, 3, 4) val result = numbers.reduce { acc, num -> acc * num } println(result)
Attempts:
2 left
💡 Hint
Reduce starts with the first element and multiplies all elements.
✗ Incorrect
Reduce multiplies 2 * 3 = 6, then 6 * 4 = 24. So the output is 24.
❓ Predict Output
advanced2:00remaining
What error does this reduce call cause?
What happens when you run this Kotlin code?
Kotlin
val emptyList = emptyList<Int>() val result = emptyList.reduce { acc, num -> acc + num } println(result)
Attempts:
2 left
💡 Hint
Reduce requires at least one element in the list.
✗ Incorrect
Calling reduce on an empty list throws UnsupportedOperationException because there is no initial element to start with.
❓ Predict Output
advanced2:00remaining
What is the output of this foldRight operation?
What will this Kotlin code print?
Kotlin
val letters = listOf("a", "b", "c") val result = letters.foldRight("") { letter, acc -> acc + letter } println(result)
Attempts:
2 left
💡 Hint
foldRight starts from the right end of the list.
✗ Incorrect
foldRight applies the operation starting from the right: acc starts as "". Then acc + "c" = "c", then "c" + "b" = "cb", then "cb" + "a" = "cba".
🧠 Conceptual
expert2:00remaining
How many elements are in the resulting list after this fold?
Given this Kotlin code, how many elements does
result contain?Kotlin
val numbers = listOf(1, 2, 3) val result = numbers.fold(mutableListOf<Int>()) { acc, num -> acc.add(num * 2) acc } println(result.size)
Attempts:
2 left
💡 Hint
fold can accumulate results in a mutable collection.
✗ Incorrect
The fold starts with an empty mutable list. For each number, it adds the doubled value. After processing 3 numbers, the list has 3 elements.