Generic interface declaration in Typescript - Time & Space Complexity
We want to understand how the time it takes to use a generic interface changes as the input size grows.
Specifically, how does the code inside the interface behave when handling different amounts of data?
Analyze the time complexity of the following code snippet.
interface Box<T> {
contents: T[];
add(item: T): void;
get(index: number): T | undefined;
}
class SimpleBox<T> implements Box<T> {
contents: T[] = [];
add(item: T) { this.contents.push(item); }
get(index: number) { return this.contents[index]; }
}
This code defines a generic interface and a class that stores items in an array, allowing adding and getting items by index.
- Primary operation: Adding an item uses array push (amortized constant time), getting an item accesses array by index (constant time).
- How many times: Each add or get operation happens once per call, no loops inside these methods.
Each add or get operation takes about the same time no matter how many items are stored.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 operations for 10 adds or gets |
| 100 | 100 operations for 100 adds or gets |
| 1000 | 1000 operations for 1000 adds or gets |
Pattern observation: The time grows directly with the number of calls, but each call is quick and does not depend on the total size.
Time Complexity: O(1)
This means each add or get operation takes the same small amount of time no matter how many items are stored.
[X] Wrong: "Adding or getting items takes longer as the box fills up because the array grows."
[OK] Correct: The array push and index access are designed to be very fast and do not slow down with more items.
Understanding how generic interfaces work with data storage helps you explain how your code handles different data sizes efficiently.
"What if the get method searched for an item by value instead of index? How would the time complexity change?"