0
0
Kotlinprogramming~20 mins

Fold and reduce operations in Kotlin - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Fold and Reduce Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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)
A14
B0
C4
D-10
Attempts:
2 left
💡 Hint
Remember that fold starts with the initial value and applies the operation from left to right.
Predict Output
intermediate
2: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)
A24
B9
C20
D14
Attempts:
2 left
💡 Hint
Reduce starts with the first element and multiplies all elements.
Predict Output
advanced
2: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)
ANo output, prints 0
BPrints null
CThrows NullPointerException
DThrows UnsupportedOperationException
Attempts:
2 left
💡 Hint
Reduce requires at least one element in the list.
Predict Output
advanced
2: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)
A""
B"abc"
C"cba"
D"cab"
Attempts:
2 left
💡 Hint
foldRight starts from the right end of the list.
🧠 Conceptual
expert
2: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)
A3
B0
C1
DThrows an exception
Attempts:
2 left
💡 Hint
fold can accumulate results in a mutable collection.