0
0
Kotlinprogramming~5 mins

Lambda syntax and declaration in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Lambda syntax and declaration
O(n)
Understanding Time 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?

Scenario Under Consideration

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

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The lambda inside map runs once for each item in the list.
  • How many times: Exactly as many times as there are items in the list.
How Execution Grows With Input

Each item in the list causes one lambda call, so more items mean more calls.

Input Size (n)Approx. Operations
1010 lambda calls
100100 lambda calls
10001000 lambda calls

Pattern observation: The number of operations grows directly with the number of items.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line with the input size.

Common Mistake

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

Interview Connect

Understanding how lambdas run helps you explain code efficiency clearly and confidently.

Self-Check

"What if we replaced map with filter? How would the time complexity change?"