Testing scope functions and lambdas in Kotlin - Time & Space Complexity
We want to understand how the time it takes to run Kotlin collection functions and lambdas changes as the input grows.
How does the number of operations increase when using these functions with larger data?
Analyze the time complexity of the following code snippet.
val numbers = listOf(1, 2, 3, 4, 5)
numbers.map { it * 2 }
.filter { it > 5 }
.forEach { println(it) }
This code doubles each number, keeps those greater than 5, and prints them.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The
map,filter, andforEacheach loop over the list. - How many times: Each function goes through all items once, so three times total over the list.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 30 (3 times 10) |
| 100 | About 300 (3 times 100) |
| 1000 | About 3000 (3 times 1000) |
Pattern observation: The total work grows directly with the size of the list, multiplied by the number of functions called.
Time Complexity: O(n)
This means the time to run grows in a straight line as the input list gets bigger.
[X] Wrong: "Using multiple collection functions like map and filter makes the code run in constant time because they are built-in."
[OK] Correct: Each collection function processes the whole list once, so the total time grows with the input size, not fixed.
Understanding how collection functions and lambdas affect performance helps you write clear and efficient Kotlin code, a skill valued in many coding challenges and real projects.
"What if we combined map and filter into a single loop using sequence? How would the time complexity change?"