0
0
Kotlinprogramming~5 mins

FlatMap for nested collections in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: FlatMap for nested collections
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

As the total number of elements inside all inner lists grows, the work grows roughly the same amount.

Input Size (total elements)Approx. Operations
10About 10 operations
100About 100 operations
1000About 1000 operations

Pattern observation: The time grows directly with the total number of elements across all inner lists.

Final Time Complexity

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.

Common Mistake

[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.

Interview Connect

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.

Self-Check

What if we replaced map inside flatMap with a filter that sometimes skips elements? How would the time complexity change?