Returning functions from functions in Kotlin - Time & Space 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?
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 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.
The multiplication inside the returned function takes the same time no matter the input size.
| Number of Calls (n) | Approx. Operations |
|---|---|
| 10 | 10 multiplications |
| 100 | 100 multiplications |
| 1000 | 1000 multiplications |
Pattern observation: The work grows linearly with how many times you call the returned function.
Time Complexity: O(n)
This means the total time grows directly with the number of times you call the returned function.
[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.
Understanding how returned functions work helps you explain how code runs step-by-step, a skill useful in many coding challenges.
"What if the returned function did a loop inside it? How would the time complexity change?"