Generic class syntax in Typescript - Time & Space Complexity
We want to understand how the time it takes to run a generic class changes as we use it with different amounts of data.
How does the size of the input affect the work done inside the generic class?
Analyze the time complexity of the following code snippet.
class Box<T> {
items: T[] = [];
add(item: T) {
this.items.push(item);
}
get(index: number): T | undefined {
return this.items[index];
}
}
This code defines a generic class that stores items and allows adding and retrieving them by index.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Adding an item to the array using push.
- How many times: Once per add call, no loops inside add or get methods.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 push operations |
| 100 | 100 push operations |
| 1000 | 1000 push operations |
Pattern observation: Each add call does a simple push, so operations grow directly with the number of items added.
Time Complexity: O(n)
This means the time to add n items grows in a straight line with n; doubling items roughly doubles the time.
[X] Wrong: "Using a generic class makes operations slower because of extra type handling."
[OK] Correct: Generics in TypeScript are erased at runtime, so they do not add extra time cost to operations.
Understanding how generic classes behave helps you explain how your code scales and stays efficient when handling different data types.
"What if the add method searched for duplicates before adding? How would the time complexity change?"