Type-safe builder pattern in Typescript - Time & Space 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?
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.
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.
As you add more parts, the work to join them grows with the number of parts.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Adding 10 parts + joining 10 parts |
| 100 | Adding 100 parts + joining 100 parts |
| 1000 | Adding 1000 parts + joining 1000 parts |
Pattern observation: The joining step grows linearly with the number of parts added.
Time Complexity: O(n)
This means the total work grows in a straight line as you add more parts to the builder.
[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.
Understanding how builder patterns scale helps you design clean and efficient code, a skill valued in many coding challenges.
"What if the build() method joined parts multiple times during building? How would that affect time complexity?"