0
0
Typescriptprogramming~5 mins

Generic class syntax in Typescript - Time & Space Complexity

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

Scenario Under Consideration

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

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.
How Execution Grows With Input

Explain the growth pattern intuitively.

Input Size (n)Approx. Operations
1010 push operations
100100 push operations
10001000 push operations

Pattern observation: Each add call does a simple push, so operations grow directly with the number of items added.

Final Time Complexity

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.

Common Mistake

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

Interview Connect

Understanding how generic classes behave helps you explain how your code scales and stays efficient when handling different data types.

Self-Check

"What if the add method searched for duplicates before adding? How would the time complexity change?"