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?