Flow operators (map, filter, transform) in Kotlin - Time & Space Complexity
When using flow operators like map, filter, and transform, it's important to know how the time to process data changes as the data grows.
We want to understand how the number of operations grows when we apply these operators on a flow of items.
Analyze the time complexity of the following code snippet.
import kotlinx.coroutines.flow.*
fun processNumbers(numbers: Flow): Flow = numbers
.filter { it % 2 == 0 } // keep even numbers
.map { it * 2 } // double each number
.transform { value ->
emit(value)
emit(value + 1) // emit value and value+1
}
This code filters even numbers, doubles them, then emits each doubled number plus one more value for each.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Each item in the flow is processed once through filter, map, and transform.
- How many times: For n items, each operator runs n times in sequence.
Each item goes through three steps, so the total work grows directly with the number of items.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 30 operations (3 per item) |
| 100 | About 300 operations |
| 1000 | About 3000 operations |
Pattern observation: The total operations increase in a straight line as input size grows.
Time Complexity: O(n)
This means the time to process the flow grows directly in proportion to the number of items.
[X] Wrong: "Using multiple flow operators multiplies the time complexity, making it worse than linear."
[OK] Correct: Each operator processes items one after another, so the total work adds up linearly, not multiplies exponentially.
Understanding how flow operators scale helps you write efficient reactive code and explain your reasoning clearly in interviews.
What if we added a nested loop inside the transform operator? How would the time complexity change?