0
0
Typescriptprogramming~5 mins

Abstract classes in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Abstract classes
O(n)
Understanding Time Complexity

We want to understand how the time it takes to run code with abstract classes changes as the input grows.

Specifically, how does using abstract classes affect the number of steps the program takes?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


abstract class Shape {
  abstract area(): number;
}

class Square extends Shape {
  constructor(private side: number) { super(); }
  area() { return this.side * this.side; }
}

function totalArea(shapes: Shape[]): number {
  let sum = 0;
  for (const shape of shapes) {
    sum += shape.area();
  }
  return sum;
}
    

This code defines an abstract class and calculates the total area of many shapes by calling their area method.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through the array of shapes and calling area() on each.
  • How many times: Once for each shape in the input array.
How Execution Grows With Input

Each shape requires one call to area(), so the total steps grow directly with the number of shapes.

Input Size (n)Approx. Operations
1010 calls to area() and 10 loop steps
100100 calls to area() and 100 loop steps
10001000 calls to area() and 1000 loop steps

Pattern observation: The work grows evenly as the number of shapes increases.

Final Time Complexity

Time Complexity: O(n)

This means the time to calculate total area grows in a straight line with the number of shapes.

Common Mistake

[X] Wrong: "Using abstract classes makes the code slower because of extra overhead."

[OK] Correct: The abstract class itself does not add extra loops or repeated work; it just defines a structure. The main cost depends on how many shapes you process.

Interview Connect

Understanding how abstract classes affect time helps you explain design choices clearly and shows you know how structure relates to performance.

Self-Check

"What if each shape's area() method did a complex calculation with its own loops? How would the time complexity change?"