0
0
Typescriptprogramming~5 mins

Parameters type in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Parameters type
O(n)
Understanding Time Complexity

We want to see how the time to run a function changes when we use different types of parameters.

How does the input type affect the work the function does?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


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

const values = [1, 2, 3, 4, 5];
sumNumbers(values);
    

This function adds up all numbers in an array and returns the total.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through each number in the array.
  • How many times: Once for every number in the input array.
How Execution Grows With Input

As the array gets bigger, 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 items.

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows in a straight line with the input size.

Common Mistake

[X] Wrong: "Changing the parameter type to a single number instead of an array will keep the same time complexity."

[OK] Correct: A single number means no loop is needed, so the time does not grow with input size anymore.

Interview Connect

Understanding how input types affect time helps you explain your code clearly and shows you think about efficiency.

Self-Check

"What if the parameter was a nested array of numbers? How would the time complexity change?"