FlatMap for nested collections in Kotlin - Time & Space Complexity
When using flatMap on nested collections, it is important to understand how the time to run grows as the collections get bigger.
We want to know how many steps the program takes when it combines all inner lists into one big list.
Analyze the time complexity of the following code snippet.
val nestedList = listOf(
listOf(1, 2, 3),
listOf(4, 5),
listOf(6, 7, 8, 9)
)
val flatList = nestedList.flatMap { innerList ->
innerList.map { it * 2 }
}
This code takes a list of lists of numbers, doubles each number, and then combines all results into one list.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Traversing each inner list and mapping its elements.
- How many times: Once for each element inside every inner list.
As the total number of elements inside all inner lists grows, the work grows roughly the same amount.
| Input Size (total elements) | Approx. Operations |
|---|---|
| 10 | About 10 operations |
| 100 | About 100 operations |
| 1000 | About 1000 operations |
Pattern observation: The time grows directly with the total number of elements across all inner lists.
Time Complexity: O(n)
This means the time to run grows in a straight line with the total number of elements inside all nested lists combined.
[X] Wrong: "Because there are two loops (flatMap and map), the time is squared, like O(n²)."
[OK] Correct: The inner map runs once per element, not nested inside another full loop. So the total steps add up linearly, not multiply.
Understanding how flatMap works helps you explain how data is processed step-by-step in real projects, showing you can reason about code efficiency clearly.
What if we replaced map inside flatMap with a filter that sometimes skips elements? How would the time complexity change?
Practice
flatMap function do when applied to a nested list in Kotlin?Solution
Step 1: Understand flatMap behavior
flatMapapplies a transformation to each element and then flattens the nested results into one list.Step 2: Compare with other functions
Unlike sorting, filtering, or converting to a set,flatMapcombines mapping and flattening in one step.Final Answer:
It transforms each element and flattens the result into a single list. -> Option CQuick Check:
flatMap = transform + flatten [OK]
- Confusing flatMap with filter or sort
- Thinking flatMap removes duplicates
- Assuming flatMap only maps without flattening
flatMap on a list of lists named nestedList in Kotlin?Solution
Step 1: Identify correct lambda syntax
TheflatMapfunction requires a lambda to transform each element.{ it }returns each inner list as is.Step 2: Check other options
nestedList.flatMap() misses lambda, C uses wrong arrow syntax, D uses flatten() incorrectly on flat inner lists.Final Answer:
nestedList.flatMap { it } -> Option AQuick Check:
flatMap needs a lambda like { it } [OK]
- Omitting the lambda block
- Using arrow (->) instead of curly braces
- Using flatten() instead of identity mapping
val nested = listOf(listOf(1, 2), listOf(3, 4))
val result = nested.flatMap { it.map { it * 2 } }
println(result)Solution
Step 1: Understand inner map transformation
Each inner list element is multiplied by 2, so listOf(1,2) becomes listOf(2,4), and listOf(3,4) becomes listOf(6,8).Step 2: Apply flatMap flattening
flatMapflattens the transformed lists into one list: [2, 4, 6, 8].Final Answer:
[2, 4, 6, 8] -> Option DQuick Check:
flatMap + map doubles and flattens [OK]
- Expecting nested lists instead of flat list
- Ignoring the inner map multiplication
- Confusing output with original nested list
flatMap:
val nested = listOf(listOf(1, 2), listOf(3, 4))
val result = nested.flatMap { it * 2 }
println(result)Solution
Step 1: Analyze the lambda expression
The lambda tries to multiplyit(a list) by 2, which is invalid in Kotlin.Step 2: Understand flatMap requirements
flatMapexpects a lambda returning an iterable, butit * 2causes a type error.Final Answer:
Cannot multiply a list by an integer directly. -> Option BQuick Check:
List * Int is invalid in Kotlin [OK]
- Assuming list * number works like in some other languages
- Thinking flatMap needs a filter
- Confusing map and flatMap usage
flatMap to get a single list of all grades above 70?
data class Student(val name: String, val grades: List<Int>)
val students = listOf(
Student("Alice", listOf(80, 65)),
Student("Bob", listOf(90, 72)),
Student("Carol", listOf(60, 85))
)
// Fill in the blank:
val passingGrades = students.flatMap { ________ }
println(passingGrades)Solution
Step 1: Filter grades above 70 for each student
Inside the lambda, useit.grades.filter { grade -> grade > 70 }to keep only passing grades.Step 2: Use flatMap to flatten all filtered grades
flatMapcombines all filtered lists into one flat list of passing grades.Final Answer:
it.grades.filter { grade -> grade > 70 } -> Option AQuick Check:
flatMap + filter extracts and flattens passing grades [OK]
- Using map instead of filter, resulting in booleans
- Filtering for grades below 70 by mistake
- Not filtering and returning all grades
Ready to prove it?
Pass the test and this pattern moves unknown
