String type behavior in Typescript - Time & Space Complexity
We want to understand how the time to work with strings changes as the string gets longer.
How does the length of a string affect the time it takes to do common operations?
Analyze the time complexity of the following code snippet.
function countChars(str: string, charToCount: string): number {
let count = 0;
for (let i = 0; i < str.length; i++) {
if (str[i] === charToCount) {
count++;
}
}
return count;
}
This code counts how many times a specific character appears in a string.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each character of the string once.
- How many times: Exactly once for each character in the string (str.length times).
As the string gets longer, the time to count characters grows in a straight line.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks |
| 100 | 100 checks |
| 1000 | 1000 checks |
Pattern observation: Doubling the string length doubles the work needed.
Time Complexity: O(n)
This means the time to count characters grows directly with the string length.
[X] Wrong: "Accessing a character in a string is slow and adds extra loops."
[OK] Correct: Accessing a character by index is fast and does not add loops; the main time is from the single loop over the string.
Understanding how string operations scale helps you write efficient code and explain your reasoning clearly in interviews.
"What if we searched for a substring instead of a single character? How would the time complexity change?"