0
0
Typescriptprogramming~5 mins

Implementing interfaces in classes in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Implementing interfaces in classes
O(n)
Understanding Time Complexity

When a class follows an interface, it must provide certain actions. We want to see how the time to run these actions changes as we use bigger inputs.

How does the work inside these class methods grow when input size grows?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


interface Logger {
  logMessages(messages: string[]): void;
}

class ConsoleLogger implements Logger {
  logMessages(messages: string[]): void {
    for (const msg of messages) {
      console.log(msg);
    }
  }
}
    

This code defines an interface with a method to log messages. The class implements it by printing each message one by one.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through the array of messages.
  • How many times: Once for each message in the input array.
How Execution Grows With Input

Explain the growth pattern intuitively.

Input Size (n)Approx. Operations
1010 console logs
100100 console logs
10001000 console logs

Pattern observation: The work grows directly with the number of messages. Double the messages, double the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to log messages grows in a straight line with the number of messages.

Common Mistake

[X] Wrong: "Implementing an interface makes the code run faster or slower by itself."

[OK] Correct: The interface only sets rules. The speed depends on what the methods actually do, not on the interface itself.

Interview Connect

Understanding how your class methods scale with input size shows you can write efficient code that works well as data grows. This skill is useful in many coding tasks.

Self-Check

"What if the logMessages method also called another method inside the class that loops over the messages again? How would the time complexity change?"