0
0
Typescriptprogramming~5 mins

Constructor parameter types in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Constructor parameter types
O(n)
Understanding Time Complexity

Let's see how the time it takes to run code changes when we use constructor parameters in TypeScript classes.

We want to know how the number of operations grows as we create more objects with parameters.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


class Person {
  name: string;
  age: number;

  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }
}

const people: Person[] = [];
for (let i = 0; i < n; i++) {
  people.push(new Person(`Name${i}`, i));
}
    

This code creates a list of Person objects, each with a name and age passed to the constructor.

Identify Repeating Operations
  • Primary operation: Creating a new Person object inside a loop.
  • How many times: The loop runs n times, so the constructor runs n times.
How Execution Grows With Input

Each time we add one more person, we do one more constructor call and one more push to the array.

Input Size (n)Approx. Operations
10About 10 constructor calls and 10 pushes
100About 100 constructor calls and 100 pushes
1000About 1000 constructor calls and 1000 pushes

Pattern observation: The number of operations grows directly with n, so doubling n doubles the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to create all objects grows in a straight line as we add more items.

Common Mistake

[X] Wrong: "The constructor runs only once, so the time is constant regardless of n."

[OK] Correct: The constructor runs every time we create a new object, so it runs n times when we create n objects.

Interview Connect

Understanding how constructors affect performance helps you explain object creation costs clearly and confidently in real projects.

Self-Check

"What if the constructor did some extra work inside a loop for each object? How would the time complexity change?"