0
0
Typescriptprogramming~5 mins

Polymorphism through interfaces in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Polymorphism through interfaces
O(n)
Understanding Time Complexity

We want to understand how the time it takes to run code changes when using polymorphism with interfaces.

Specifically, how does calling methods through interfaces affect the number of steps the program takes?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


interface Shape {
  area(): number;
}

class Circle implements Shape {
  constructor(private radius: number) {}
  area() { return Math.PI * this.radius * this.radius; }
}

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

This code calculates the total area of many shapes by calling the area method on each shape through an interface.

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 as the number of shapes grows.

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

Final Time Complexity

Time Complexity: O(n)

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

Common Mistake

[X] Wrong: "Calling methods through interfaces makes the code slower in a way that changes the time complexity."

[OK] Correct: Calling methods via interfaces adds a tiny fixed cost per call but does not change how the total steps grow with input size.

Interview Connect

Understanding how polymorphism affects time helps you explain your code's efficiency clearly and confidently.

Self-Check

"What if the area() method itself contained a loop over a list of points? How would the time complexity change?"