0
0
Typescriptprogramming~5 mins

Type-safe builder pattern in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Type-safe builder pattern
O(n)
Understanding Time Complexity

We want to understand how the time it takes to build an object grows as we add more steps in a type-safe builder pattern.

How does the number of builder method calls affect the total work done?

Scenario Under Consideration

Analyze the time complexity of the following TypeScript builder pattern code.


class Builder {
  private parts: string[] = [];

  addPart(part: string): this {
    this.parts.push(part);
    return this;
  }

  build(): string {
    return this.parts.join(", ");
  }
}
    

This code builds a string by adding parts one by one, then joining them all at the end.

Identify Repeating Operations

Look for loops or repeated work in the builder.

  • Primary operation: Adding parts to an array and joining them.
  • How many times: Each addPart call adds one element; build joins all parts once.
How Execution Grows With Input

As you add more parts, the work to join them grows with the number of parts.

Input Size (n)Approx. Operations
10Adding 10 parts + joining 10 parts
100Adding 100 parts + joining 100 parts
1000Adding 1000 parts + joining 1000 parts

Pattern observation: The joining step grows linearly with the number of parts added.

Final Time Complexity

Time Complexity: O(n)

This means the total work grows in a straight line as you add more parts to the builder.

Common Mistake

[X] Wrong: "Each addPart call does a lot of work, so the builder is slow."

[OK] Correct: Each addPart just adds one item quickly; the main work happens once when build() joins all parts.

Interview Connect

Understanding how builder patterns scale helps you design clean and efficient code, a skill valued in many coding challenges.

Self-Check

"What if the build() method joined parts multiple times during building? How would that affect time complexity?"