0
0
Typescriptprogramming~5 mins

Builder pattern with generics in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Builder pattern with generics
O(n)
Understanding Time Complexity

We want to see how the time needed to build an object changes as we add more parts using the builder pattern with generics.

How does the number of steps grow when the builder handles more properties?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


class Builder<T> {
  private obj: Partial<T> = {};

  set<K extends keyof T>(key: K, value: T[K]): this {
    this.obj[key] = value;
    return this;
  }

  build(): T {
    return this.obj as T;
  }
}
    

This code builds an object step-by-step by setting properties one at a time, using generics to keep track of property types.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Each call to set adds or updates one property in the object.
  • How many times: The set method is called once per property you want to add.
How Execution Grows With Input

Each property added requires one step, so the total steps grow directly with the number of properties.

Input Size (n)Approx. Operations
1010 steps to set properties
100100 steps to set properties
10001000 steps to set properties

Pattern observation: The work grows evenly as you add more properties, like counting one by one.

Final Time Complexity

Time Complexity: O(n)

This means the time to build the object grows in a straight line with the number of properties you add.

Common Mistake

[X] Wrong: "The builder sets all properties at once, so time is constant no matter how many properties."

[OK] Correct: Each property requires a separate set call, so time grows with how many properties you add.

Interview Connect

Understanding how building objects step-by-step affects time helps you explain design choices clearly and shows you think about efficiency in real code.

Self-Check

What if the build method also validated all properties before returning? How would the time complexity change?