Generic interface for collections in Typescript - Time & Space Complexity
When working with generic interfaces for collections, it's important to know how the time to perform actions changes as the collection grows.
We want to find out how the number of steps grows when we add or check items in the collection.
Analyze the time complexity of the following code snippet.
interface Collection<T> {
add(item: T): void;
contains(item: T): boolean;
}
class SimpleCollection<T> implements Collection<T> {
private items: T[] = [];
add(item: T): void {
this.items.push(item);
}
contains(item: T): boolean {
return this.items.includes(item);
}
}
This code defines a generic collection interface and a simple class that stores items in an array. It adds items and checks if an item exists.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The
containsmethod usesincludes, which checks each item one by one. - How many times: It may check up to all items in the array, depending on where the item is found.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Up to 10 checks |
| 100 | Up to 100 checks |
| 1000 | Up to 1000 checks |
Pattern observation: The number of checks grows directly with the number of items. More items mean more steps to find one.
Time Complexity: O(n)
This means the time to check if an item exists grows in a straight line with the number of items in the collection.
[X] Wrong: "Checking if an item exists is always fast and takes the same time no matter how many items there are."
[OK] Correct: Because the method checks items one by one, more items mean more checks, so it takes longer as the collection grows.
Understanding how generic collections work and how their operations scale helps you explain your code choices clearly and confidently in real projects and interviews.
"What if we changed the internal storage from an array to a Set? How would the time complexity of contains change?"
Practice
<T> represent in a generic interface in TypeScript?Solution
Step 1: Understand generic syntax
The<T>in TypeScript generics is a placeholder representing any type that will be provided when the interface is used.Step 2: Differentiate from fixed types
Unlike fixed types likenumberorstring,Tis flexible and can represent any type, making the interface reusable.Final Answer:
A placeholder for any type that will be specified later -> Option CQuick Check:
Generic<T>= placeholder type [OK]
<T> means 'any type' placeholder [OK]- Thinking
Tis a fixed type - Confusing
Twith a function - Assuming
Tis a variable name
Collection with a type parameter T?Solution
Step 1: Check generic declaration
The correct syntax to declare a generic interface uses<T>after the interface name, likeinterface Collection<T>.Step 2: Verify property type
The propertyitemsshould be an array of typeT, soitems: T[]is correct.Final Answer:
interface Collection<T> { items: T[]; } -> Option AQuick Check:
Generic interface syntax = interface Collection<T> { items: T[]; } [OK]
<T> and array type T[] [OK]- Omitting
<T>after interface name - Using
Arraywithout type parameter - Declaring items as single
Tinstead of array
console.log(numbers.items[1])?
interface Collection<T> {
items: T[];
}
const numbers: Collection<number> = { items: [10, 20, 30] };
console.log(numbers.items[1]);Solution
Step 1: Understand the generic interface usage
The interfaceCollection<T>is used withnumber, soitemsis an array of numbers: [10, 20, 30].Step 2: Access the second element in the array
Arrays are zero-indexed, soitems[1]is the second element, which is 20.Final Answer:
20 -> Option BQuick Check:
Array index 1 = 20 [OK]
- Confusing index 1 with index 0
- Assuming generic changes array order
- Expecting undefined for valid index
interface Collection<T> {
items: T[];
}
const strings: Collection<string> = { items: [1, 2, 3] };Solution
Step 1: Check the generic type used
The variablestringsis declared asCollection<string>, soitemsmust be an array of strings.Step 2: Check the assigned array type
The assigned array is[1, 2, 3], which is an array of numbers, not strings, causing a type mismatch error.Final Answer:
The array items contain numbers, but the interface expects strings -> Option AQuick Check:
Type mismatch in generic array = The array items contain numbers, but the interface expects strings [OK]
- Ignoring type mismatch between generic and array
- Forgetting to specify generic parameter
- Assuming interface property can be non-array
KeyValueCollection that stores key-value pairs where keys are strings and values can be any type T. Which interface definition correctly achieves this?Solution
Step 1: Understand key-value pair requirement
The interface should allow any string as a key and associate it with a value of generic typeT.Step 2: Check index signature syntax
Using[key: string]: T;means any string key maps to a value of typeT, which matches the requirement.Step 3: Eliminate other options
interface KeyValueCollection<T> { keys: string[]; values: T[]; } separates keys and values arrays, which is less direct. interface KeyValueCollection<T> { key: string; value: T; } defines a single pair, not a collection. interface KeyValueCollection<T> { [T: string]: string; } has incorrect syntax.Final Answer:
interface KeyValueCollection<T> { [key: string]: T; } -> Option DQuick Check:
Index signature with generic value = interface KeyValueCollection<T> { [key: string]: T; } [OK]
- Using arrays for keys and values separately
- Defining only one key-value pair instead of collection
- Incorrect index signature syntax
Ready to prove it?
Pass the test and this pattern moves unknown
