Vararg parameters in Kotlin - Time & Space Complexity
We want to understand how the time to run a function changes when it accepts a variable number of arguments.
How does the function's work grow as we give it more inputs?
Analyze the time complexity of the following code snippet.
fun sumAll(vararg numbers: Int): Int {
var sum = 0
for (num in numbers) {
sum += num
}
return sum
}
This function adds up all the numbers passed to it using a vararg parameter.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each number in the vararg array.
- How many times: Once for each number passed to the function.
As you give more numbers, the function adds each one, so the work grows steadily.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The work grows directly with the number of inputs.
Time Complexity: O(n)
This means the time to run the function grows in a straight line with the number of arguments.
[X] Wrong: "Vararg parameters make the function run instantly no matter how many inputs."
[OK] Correct: The function still processes each input one by one, so more inputs mean more work.
Understanding how vararg parameters affect time helps you explain how flexible functions handle many inputs efficiently.
"What if we changed the function to call itself recursively for each number? How would the time complexity change?"