0
0
Typescriptprogramming~5 mins

Generic class with constraints in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Generic class with constraints
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The find method loops through the items array to check each item's id.
  • How many times: It checks each item once until it finds a match or reaches the end.
How Execution Grows With Input

As the number of items grows, the time to find an item grows roughly the same way.

Input Size (n)Approx. Operations
10Up to 10 checks
100Up to 100 checks
1000Up to 1000 checks

Pattern observation: The work grows directly with the number of items.

Final Time Complexity

Time Complexity: O(n)

This means the time to find an item grows linearly as the list gets longer.

Common Mistake

[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.

Interview Connect

Understanding how generic classes work with constraints and their time costs helps you explain your code clearly and shows you think about efficiency.

Self-Check

"What if we changed the items array to a Map keyed by id? How would the time complexity change?"