0
0
Kotlinprogramming~5 mins

Passing lambdas to functions in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Passing lambdas to functions
O(n)
Understanding Time Complexity

When we pass lambdas (small blocks of code) to functions, it's important to see how this affects the time the program takes to run.

We want to know how the number of times the lambda runs changes as the input grows.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


fun applyToList(numbers: List, action: (Int) -> Unit) {
    for (number in numbers) {
        action(number)
    }
}

fun main() {
    val nums = listOf(1, 2, 3, 4, 5)
    applyToList(nums) { println(it) }
}
    

This code runs a given lambda on each item in a list, printing each number.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for-loop that goes through each item in the list.
  • How many times: Once for every item in the list.
How Execution Grows With Input

As the list gets bigger, the lambda runs more times, once per item.

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

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

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line with the number of items.

Common Mistake

[X] Wrong: "Passing a lambda makes the code run slower in a way that multiplies the work."

[OK] Correct: The lambda runs once per item, just like any code inside the loop. It doesn't add hidden extra loops or repeats.

Interview Connect

Understanding how lambdas affect time helps you explain your code clearly and shows you know how to reason about performance in real projects.

Self-Check

"What if the lambda itself contains a loop over the list? How would the time complexity change?"