0
0
Typescriptprogramming~5 mins

Access modifiers public private protected in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Access modifiers public private protected
O(n)
Understanding Time Complexity

Let's see how using access modifiers affects the speed of running TypeScript code.

We want to know if public, private, or protected changes how long the program takes as it grows.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


class Counter {
  private count = 0;

  public increment() {
    this.count++;
  }

  protected getCount() {
    return this.count;
  }
}

const counter = new Counter();
for (let i = 0; i < 1000; i++) {
  counter.increment();
}

This code defines a class with public, private, and protected parts, then calls a method many times.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The loop calling increment() 1000 times.
  • How many times: Exactly 1000 times, each increasing the count by one.
How Execution Grows With Input

Explain the growth pattern intuitively.

Input Size (n)Approx. Operations
1010 increments
100100 increments
10001000 increments

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

Final Time Complexity

Time Complexity: O(n)

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

Common Mistake

[X] Wrong: "Using private or protected slows down the code because of extra checks."

[OK] Correct: Access modifiers are for organizing code and controlling access, but they do not add extra time when running loops or methods.

Interview Connect

Understanding that access modifiers do not affect how fast your code runs helps you focus on writing clear and safe code without worrying about speed.

Self-Check

"What if the increment method called another method inside the class multiple times? How would the time complexity change?"