0
0
Typescriptprogramming~5 mins

Method overriding with types in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Method overriding with types
O(n)
Understanding Time Complexity

We want to understand how the time it takes to run code changes when using method overriding with types in TypeScript.

Specifically, we ask: how does the program's work grow as input or calls increase?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


class Animal {
  speak(): string {
    return "...";
  }
}

class Dog extends Animal {
  speak(): string {
    return "Woof!";
  }
}

function makeSpeak(animal: Animal) {
  return animal.speak();
}

const dog = new Dog();
makeSpeak(dog);
    

This code shows a base class with a method, a subclass that overrides it, and a function calling the method on an object.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Calling the speak method on an object.
  • How many times: Once per call to makeSpeak. No loops or recursion here.
How Execution Grows With Input

Since there is no loop or repeated calls inside the snippet, the work grows directly with how many times makeSpeak is called.

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

Pattern observation: The time grows linearly with the number of calls.

Final Time Complexity

Time Complexity: O(n)

This means if you call the method n times, the total work grows roughly in direct proportion to n.

Common Mistake

[X] Wrong: "Overriding a method makes the program slower by adding hidden loops or extra work."

[OK] Correct: Overriding just changes which code runs when the method is called. It does not add loops or repeated work by itself.

Interview Connect

Understanding how method calls and overriding affect performance helps you explain code behavior clearly and confidently in interviews.

Self-Check

"What if the speak method called itself recursively? How would the time complexity change?"