Multiple generic parameters in Typescript - Time & Space 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?
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 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.
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, 10 | 20 |
| 100, 100 | 200 |
| 1000, 1000 | 2000 |
Pattern observation: The total work grows roughly by adding the sizes of both inputs.
Time Complexity: O(n + m)
This means the time grows in a straight line with the total number of items in both arrays combined.
[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.
Understanding how multiple inputs affect time helps you explain your code clearly and shows you can think about efficiency in real situations.
"What if the two loops were nested instead of separate? How would the time complexity change?"