Lambda syntax and declaration in Kotlin - Time & Space Complexity
When we use lambdas in Kotlin, we want to know how fast they run as the input grows.
We ask: How does the time to run a lambda change when we give it more data?
Analyze the time complexity of the following code snippet.
val numbers = listOf(1, 2, 3, 4, 5)
val doubled = numbers.map { it * 2 }
println(doubled)
This code uses a lambda to double each number in a list.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The lambda inside
mapruns once for each item in the list. - How many times: Exactly as many times as there are items in the list.
Each item in the list causes one lambda call, so more items mean more calls.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 lambda calls |
| 100 | 100 lambda calls |
| 1000 | 1000 lambda calls |
Pattern observation: The number of operations grows directly with the number of items.
Time Complexity: O(n)
This means the time to run grows in a straight line with the input size.
[X] Wrong: "The lambda runs only once no matter the list size."
[OK] Correct: The lambda runs for every item, so more items mean more runs.
Understanding how lambdas run helps you explain code efficiency clearly and confidently.
"What if we replaced map with filter? How would the time complexity change?"