Building type-safe string patterns in Typescript - Time & Space Complexity
When building type-safe string patterns, it is important to know how the time to check or build these patterns grows as the input changes.
We want to understand how the program's work increases when the strings or patterns get longer or more complex.
Analyze the time complexity of the following code snippet.
function buildPattern(parts: string[]): string {
let pattern = '';
for (const part of parts) {
pattern += `\\${part}`;
}
return pattern;
}
const parts = ['d', 'w', 's'];
const result = buildPattern(parts);
This code builds a string pattern by joining parts with a backslash before each part.
- Primary operation: Looping through each string in the parts array.
- How many times: Once for each element in the parts array (n times).
As the number of parts increases, the loop runs more times, adding more to the pattern string.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 string concatenations |
| 100 | About 100 string concatenations |
| 1000 | About 1000 string concatenations |
Pattern observation: The work grows directly with the number of parts; doubling parts doubles the work.
Time Complexity: O(n^2)
This means the time to build the pattern grows quadratically as the number of parts increases, due to repeated string concatenations.
[X] Wrong: "Adding more parts won't affect performance much because strings are fast to join."
[OK] Correct: Each addition creates a new string, so more parts mean more work and longer time.
Understanding how string operations scale helps you write efficient code and explain your reasoning clearly in interviews.
"What if we used an array to collect parts and joined them once at the end? How would the time complexity change?"