0
0
Kotlinprogramming~5 mins

Returning functions from functions in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Returning functions from functions
O(n)
Understanding Time Complexity

When a function returns another function, we want to know how the time it takes grows as inputs change.

We ask: How does calling the returned function affect overall work done?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


fun multiplier(factor: Int): (Int) -> Int {
    return { number: Int -> number * factor }
}

fun main() {
    val timesTwo = multiplier(2)
    println(timesTwo(10))
}
    

This code returns a function that multiplies a number by a given factor.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Multiplying two numbers inside the returned function.
  • How many times: Each time the returned function is called, once per call.
How Execution Grows With Input

The multiplication inside the returned function takes the same time no matter the input size.

Number of Calls (n)Approx. Operations
1010 multiplications
100100 multiplications
10001000 multiplications

Pattern observation: The work grows linearly with how many times you call the returned function.

Final Time Complexity

Time Complexity: O(n)

This means the total time grows directly with the number of times you call the returned function.

Common Mistake

[X] Wrong: "Returning a function means the original function does a lot of work upfront."

[OK] Correct: The original function just creates and returns a small function quickly; the real work happens when you call the returned function.

Interview Connect

Understanding how returned functions work helps you explain how code runs step-by-step, a skill useful in many coding challenges.

Self-Check

"What if the returned function did a loop inside it? How would the time complexity change?"