0
0
Typescriptprogramming~5 mins

Abstract methods in Typescript - Time & Space Complexity

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

We want to understand how using abstract methods affects the time it takes for a program to run.

Specifically, we ask: how does calling abstract methods impact the number of steps as input grows?

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; }
}

const squares: Square[] = [new Square(2), new Square(3), new Square(4)];
for (const sq of squares) {
  console.log(sq.area());
}
    

This code defines an abstract method area and calls it on several objects in a loop.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Calling the area method on each object in the array.
  • How many times: Once for each object in the squares array.
How Execution Grows With Input

Each time we add one more square, we call area one more time.

Input Size (n)Approx. Operations
1010 calls to area
100100 calls to area
10001000 calls to area

Pattern observation: The number of operations grows directly with the number of objects.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line as the number of objects increases.

Common Mistake

[X] Wrong: "Abstract methods slow down the program because they add extra steps."

[OK] Correct: Calling an abstract method is just like calling any other method; the time depends on how many times you call it, not on it being abstract.

Interview Connect

Understanding how abstract methods affect performance helps you explain design choices clearly and confidently in interviews.

Self-Check

"What if the area method itself contained a loop over a large array? How would the time complexity change?"