0
0
Typescriptprogramming~5 mins

Rest parameters with types in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Rest parameters with types
O(n)
Understanding Time Complexity

Let's see how the time needed to run a function changes when it uses rest parameters with types.

We want to know how the number of inputs affects the work done inside the function.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


function sumAll(...numbers: number[]): number {
  let total = 0;
  for (const num of numbers) {
    total += num;
  }
  return total;
}
    

This function adds up all numbers passed to it using rest parameters typed as an array of numbers.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through each number in the rest parameter array.
  • 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 finish grows in a straight line as you add more numbers.

Common Mistake

[X] Wrong: "Rest parameters make the function run instantly no matter how many inputs there are."

[OK] Correct: Even though rest parameters collect inputs nicely, the function still needs to look at each input once to add them up.

Interview Connect

Understanding how rest parameters affect time helps you explain how your functions handle many inputs clearly and confidently.

Self-Check

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