Builder pattern with generics in Typescript - Time & Space 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?
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 the loops, recursion, array traversals that repeat.
- Primary operation: Each call to
setadds or updates one property in the object. - How many times: The
setmethod is called once per property you want to add.
Each property added requires one step, so the total steps grow directly with the number of properties.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 steps to set properties |
| 100 | 100 steps to set properties |
| 1000 | 1000 steps to set properties |
Pattern observation: The work grows evenly as you add more properties, like counting one by one.
Time Complexity: O(n)
This means the time to build the object grows in a straight line with the number of properties you add.
[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.
Understanding how building objects step-by-step affects time helps you explain design choices clearly and shows you think about efficiency in real code.
What if the build method also validated all properties before returning? How would the time complexity change?