0
0
Typescriptprogramming~5 mins

Multiple generic parameters in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Multiple generic parameters
O(n + m)
Understanding Time Complexity

We want to see how the time needed changes when using multiple generic parameters in TypeScript functions or classes.

How does the work grow when both generic inputs get bigger?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


function combineArrays<T, U>(arr1: T[], arr2: U[]): (T | U)[] {
  const result: (T | U)[] = [];
  for (const item of arr1) {
    result.push(item);
  }
  for (const item of arr2) {
    result.push(item);
  }
  return result;
}
    

This function takes two arrays with different types and combines them into one array.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Two separate loops that go through each array.
  • How many times: Once for each element in the first array, and once for each element in the second array.
How Execution Grows With Input

As the size of both arrays grows, the total work grows by adding the work for each array.

Input Size (n, m)Approx. Operations
10, 1020
100, 100200
1000, 10002000

Pattern observation: The total work grows roughly by adding the sizes of both inputs.

Final Time Complexity

Time Complexity: O(n + m)

This means the time grows in a straight line with the total number of items in both arrays combined.

Common Mistake

[X] Wrong: "The time complexity is O(n * m) because there are two generic types."

[OK] Correct: The loops run one after the other, not nested. So the work adds up, it does not multiply.

Interview Connect

Understanding how multiple inputs affect time helps you explain your code clearly and shows you can think about efficiency in real situations.

Self-Check

"What if the two loops were nested instead of separate? How would the time complexity change?"