Polymorphism through interfaces in Typescript - Time & Space 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?
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 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.
Each shape requires one call to area(), so the total steps grow as the number of shapes grows.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 calls to area() |
| 100 | 100 calls to area() |
| 1000 | 1000 calls to area() |
Pattern observation: The number of operations grows directly with the number of shapes.
Time Complexity: O(n)
This means the time to compute total area grows in a straight line with the number of shapes.
[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.
Understanding how polymorphism affects time helps you explain your code's efficiency clearly and confidently.
"What if the area() method itself contained a loop over a list of points? How would the time complexity change?"