0
0
Kotlinprogramming~5 mins

Lambda with receiver concept in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Lambda with receiver concept
O(n)
Understanding Time Complexity

Let's see how the time needed to run a lambda with receiver changes as the input grows.

We want to know how the number of operations grows when using this Kotlin feature.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


fun buildStringExample(n: Int): String = buildString {
    repeat(n) {
        append("*")
    }
}
    

This code uses a lambda with receiver to build a string by adding n stars.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The repeat loop that calls append n times.
  • How many times: Exactly n times, once per loop iteration.
How Execution Grows With Input

Each time we add one more star, the loop runs one more time, so work grows steadily.

Input Size (n)Approx. Operations
1010 appends
100100 appends
10001000 appends

Pattern observation: The work grows directly in proportion to n.

Final Time Complexity

Time Complexity: O(n)

This means the time to build the string grows in a straight line as n increases.

Common Mistake

[X] Wrong: "Using a lambda with receiver makes the code run instantly regardless of n."

[OK] Correct: The lambda with receiver just changes how we write code, but the loop inside still runs n times, so time grows with n.

Interview Connect

Understanding how lambdas with receivers work helps you write clear Kotlin code and also think about how your code's speed changes with input size.

Self-Check

"What if we replaced repeat(n) with a nested loop inside the lambda? How would the time complexity change?"