Generic class with constraints in Typescript - Time & Space Complexity
We want to see how the time needed changes when using a generic class with constraints in TypeScript.
How does the program's work grow as the input size grows?
Analyze the time complexity of the following code snippet.
class Container<T extends { id: number }> {
items: T[] = [];
add(item: T) {
this.items.push(item);
}
findById(id: number): T | undefined {
return this.items.find(item => item.id === id);
}
}
This class stores items with an id and can add items or find one by its id.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The
findmethod loops through theitemsarray to check each item'sid. - How many times: It checks each item once until it finds a match or reaches the end.
As the number of items grows, the time to find an item grows roughly the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Up to 10 checks |
| 100 | Up to 100 checks |
| 1000 | Up to 1000 checks |
Pattern observation: The work grows directly with the number of items.
Time Complexity: O(n)
This means the time to find an item grows linearly as the list gets longer.
[X] Wrong: "Using a generic class with constraints makes the search faster automatically."
[OK] Correct: The generic constraint only ensures the item has an id, but the search still checks items one by one.
Understanding how generic classes work with constraints and their time costs helps you explain your code clearly and shows you think about efficiency.
"What if we changed the items array to a Map keyed by id? How would the time complexity change?"