Pattern matching with template literals in Typescript - Time & Space Complexity
We want to understand how the time it takes to match patterns using template literals changes as the input grows.
How does the matching process scale when the input string gets longer?
Analyze the time complexity of the following code snippet.
const input = "user_1234";
function matchUser(input: string): boolean {
return input.startsWith("user_");
}
console.log(matchUser(input));
This code checks if the input string starts with "user_" using a fixed prefix.
- Primary operation: Checking each character of the prefix "user_" against the input string.
- How many times: Once per character in the prefix, which is a fixed length (5 characters).
The check only looks at the first few characters, so even if the input grows, the work stays the same.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 5 (fixed prefix length) |
| 100 | 5 (still just prefix length) |
| 1000 | 5 (no change) |
Pattern observation: The number of operations does not grow with input size because only the fixed prefix is checked.
Time Complexity: O(1)
This means the time to check the pattern stays the same no matter how long the input string is.
[X] Wrong: "Matching a pattern with template literals always takes longer as the input grows."
[OK] Correct: Here, only the fixed part of the pattern is checked, so the input length does not affect the time.
Understanding how pattern matching scales helps you explain your code's efficiency clearly and confidently in interviews.
"What if the pattern included a variable-length part that must be fully checked? How would the time complexity change?"
Practice
Solution
Step 1: Understand the purpose of pattern matching
Pattern matching with template literals is used to verify if strings follow a certain pattern or format.Step 2: Relate to template literals usage
Template literals allow embedding expressions and patterns to check string shapes easily.Final Answer:
Check if a string fits a specific shape or format -> Option DQuick Check:
Pattern matching = Check string shape [OK]
- Confusing pattern matching with variable creation
- Thinking it changes variable types
- Assuming it generates functions automatically
Solution
Step 1: Identify correct template literal syntax
Template literals use backticks (`) and embed types inside ${} without quotes.Step 2: Check for correct punctuation
type ID = `${string}-${number}`; correctly uses backticks and ${} with no extra quotes.Final Answer:
type ID = `${string}-${number}`; -> Option AQuick Check:
Backticks + ${} = correct syntax [OK]
- Using single or double quotes instead of backticks
- Putting quotes inside ${} expressions
- Missing backticks around the pattern
type Email = `${string}@${string}.com`;
function isEmail(value: string): value is Email {
return /.+@.+\.com$/.test(value);
}
console.log(isEmail('user@example.com'));
console.log(isEmail('user@example.org'));Solution
Step 1: Understand the Email type pattern
The Email type expects strings like 'something@something.com'.Step 2: Analyze the isEmail function
The regex checks if the string ends with '.com' after an '@' symbol.Step 3: Check the console.log outputs
'user@example.com' matches the regex, so true; 'user@example.org' does not, so false.Final Answer:
true false -> Option CQuick Check:
Regex matches .com only = true, false [OK]
- Assuming .org matches .com pattern
- Ignoring regex anchors
- Confusing true/false order in output
type Phone = `${number}-${number}-${number}`;
function isPhone(value: string): value is Phone {
return /^\d{3}-\d{3}-\d{4}$/.test(value);
}Solution
Step 1: Compare Phone type and regex pattern
Phone type expects three numbers separated by dashes, but each ${number} matches any number, not fixed digits.Step 2: Check regex pattern details
The regex expects exactly 3 digits, then 3 digits, then 4 digits, which doesn't align with the Phone type's generic number placeholders.Final Answer:
The Phone type pattern does not match the regex format -> Option AQuick Check:
Type pattern and regex must align [OK]
- Assuming ${number} matches fixed digit counts
- Ignoring regex anchors (though present here)
- Confusing return type of type predicate functions
type UserID = `user_${number}`;
function parseUserID(id: string): UserID | null {
if (id.match(/^user_\d+$/)) {
return id as UserID;
}
return null;
}
console.log(parseUserID('user_123'));
console.log(parseUserID('admin_123'));Solution
Step 1: Understand UserID type pattern
UserID must start with 'user_' followed by a number.Step 2: Analyze parseUserID function
The function returns the id cast as UserID if it matches the regex /^user_\d+$/, else returns null.Step 3: Evaluate console.log outputs
'user_123' matches regex, so returns 'user_123'; 'admin_123' does not, so returns null.Final Answer:
'user_123' null -> Option BQuick Check:
Regex match returns id, else null [OK]
- Assuming 'admin_123' matches user pattern
- Confusing return types with casting
- Ignoring regex anchors and pattern
Ready to prove it?
Pass the test and this pattern moves unknown
