0
0
Kotlinprogramming~5 mins

Vararg parameters in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Vararg parameters
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

As you give more numbers, the function adds each one, so the work grows steadily.

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

Pattern observation: The work grows directly with the number of inputs.

Final Time Complexity

Time Complexity: O(n)

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

Common Mistake

[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.

Interview Connect

Understanding how vararg parameters affect time helps you explain how flexible functions handle many inputs efficiently.

Self-Check

"What if we changed the function to call itself recursively for each number? How would the time complexity change?"