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?"
Practice
Solution
Step 1: Understand type-safe string patterns
Type-safe string patterns use TypeScript's template literal types to enforce string formats during coding.Step 2: Identify the benefit
This enforcement helps catch errors early by ensuring strings match expected patterns before running the program.Final Answer:
They ensure strings follow a specific format at compile time. -> Option AQuick Check:
Type-safe string patterns = compile-time format check [OK]
- Thinking they improve runtime speed
- Confusing with string-to-number conversion
- Assuming they change string behavior at runtime
Solution
Step 1: Recognize template literal type syntax
Type-safe string patterns use backticks and ${} placeholders, like `https://${string}`.Step 2: Compare options
type URL = `https://${string}`; uses correct template literal syntax. Options A, B, and D use invalid or incorrect TypeScript syntax for this purpose.Final Answer:
type URL = `https://${string}`; -> Option DQuick Check:
Template literal type syntax = backticks + ${} [OK]
- Using quotes with + for concatenation in types
- Using & or | operators incorrectly
- Not using backticks for template literals
type ID = `user_${number}`;, which of the following assignments will cause a TypeScript error?Solution
Step 1: Understand the pattern
The type ID requires strings starting with 'user_' followed by a number.Step 2: Check each assignment
A is 'user_123' (valid number), B is 'user_0' (valid number), C uses template literal with number 456 (valid), D is 'user_abc' (letters, invalid).Final Answer:
const b: ID = 'user_abc'; causes error -> Option CQuick Check:
Pattern requires number after 'user_' = D error [OK]
- Assuming any string after prefix is valid
- Confusing template literal with runtime string
- Ignoring number type constraint
type Email = `${string}@${string}.com`;
const myEmail: Email = 'john.doe@gmail';Solution
Step 1: Analyze the type Email pattern
Email requires a string, then '@', then another string, then '.com' exactly.Step 2: Check the assigned value
myEmail is 'john.doe@gmail' missing the '.com' suffix, so it does not match the pattern.Final Answer:
The type Email does not allow missing '.com' suffix. -> Option BQuick Check:
Pattern requires '.com' suffix = missing causes error [OK]
- Ignoring required suffix in pattern
- Thinking '@' is invalid in template literals
- Confusing type errors with runtime errors
v1.2.3 where each number can be one or more digits. Which of these TypeScript types correctly enforces this pattern?Solution
Step 1: Understand the version pattern
The version string starts with 'v' followed by three numbers separated by dots.Step 2: Evaluate each type
A uses number for all three parts, matching the pattern exactly. B uses string, allowing invalid formats. C mixes number and string incorrectly. D misses the third number part.Final Answer:
type Version = `v${number}.${number}.${number}`; -> Option AQuick Check:
All parts as number with dots = type Version = `v${number}.${number}.${number}`; [OK]
- Using string instead of number for numeric parts
- Missing parts of the pattern
- Mixing types inconsistently
Ready to prove it?
Pass the test and this pattern moves unknown
