0
0
Swiftprogramming~5 mins

Variadic parameters in Swift - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Variadic parameters
O(n)
Understanding Time Complexity

When using variadic parameters, we want to know how the time to run the function changes as we pass more values.

How does the function handle many inputs and how long does it take?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

func sum(numbers: Int...) -> Int {
    var total = 0
    for number in numbers {
        total += number
    }
    return total
}

This function adds up all the numbers passed to it using a variadic parameter.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through each number in the variadic parameter.
  • How many times: Once for each number passed to the function.
How Execution Grows With Input

As you add more numbers, the function does more additions, one for each number.

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 grows in a straight line with the number of inputs.

Common Mistake

[X] Wrong: "Variadic 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 variadic parameters affect time helps you explain how your code scales when handling many inputs.

Self-Check

"What if we changed the function to multiply the numbers instead of adding? How would the time complexity change?"