Character Frequency Counting in DSA Typescript - Time & Space Complexity
Counting how often each character appears in a string is a common task in programming.
We want to know how the time needed grows as the string gets longer.
Analyze the time complexity of the following code snippet.
function charFrequency(str: string): Record {
const freq: Record = {};
for (const char of str) {
freq[char] = (freq[char] || 0) + 1;
}
return freq;
}
This code counts how many times each character appears in the input string.
- Primary operation: Looping through each character in the string once.
- How many times: Exactly once for each character, so as many times as the string length.
As the string gets longer, the number of steps grows directly with its length.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 steps |
| 100 | About 100 steps |
| 1000 | About 1000 steps |
Pattern observation: The work grows in a straight line with the input size.
Time Complexity: O(n)
This means the time to count characters grows directly with the string length.
[X] Wrong: "Since we check each character, the time is more like n squared because of the counting."
[OK] Correct: We only loop once through the string, updating counts in constant time, so it stays linear, not squared.
Understanding how simple loops affect time helps you explain your code clearly and shows you know how to handle data efficiently.
"What if we used nested loops to compare each character with every other character? How would the time complexity change?"
Practice
Solution
Step 1: Understand character frequency counting
Character frequency counting means counting how many times each character appears in a string.Step 2: Identify what it helps find
This counting helps us know the number of occurrences of each character, not the length or position.Final Answer:
How many times each character appears in the string -> Option AQuick Check:
Frequency counting = character counts [OK]
- Confusing frequency with string length
- Thinking it finds character positions
- Mixing frequency with first character only
Solution
Step 1: Identify data structure for frequency counting
We need an object to store keys (characters) and values (counts). An empty object is initialized with {}.Step 2: Check each option
const freq = new Map(); uses Map which is valid but not the simplest empty object. const freq = {}; correctly uses {}. const freq = []; is an array, not suitable. const freq = ''; is a string, not suitable.Final Answer:
const freq = {}; -> Option BQuick Check:
Empty object = {} [OK]
- Using array [] instead of object {}
- Using empty string '' instead of object
- Confusing Map with plain object initialization
const str = 'hello';
const freq: {[key: string]: number} = {};
for (const ch of str) {
freq[ch] = (freq[ch] || 0) + 1;
}
console.log(freq);Solution
Step 1: Loop through each character and count
Characters: 'h', 'e', 'l', 'l', 'o'. For each, increase count in freq object.Step 2: Calculate counts
'h' = 1, 'e' = 1, 'l' = 2 (appears twice), 'o' = 1.Final Answer:
{"h":1,"e":1,"l":2,"o":1} -> Option CQuick Check:
Count 'l' twice = 2 [OK]
- Counting 'l' only once
- Setting counts to zero
- Miswriting object output format
const str = 'abc';
const freq: {[key: string]: number} = {};
for (let i = 0; i <= str.length; i++) {
const ch = str[i];
freq[ch] = (freq[ch] || 0) + 1;
}
console.log(freq);Solution
Step 1: Check loop bounds
Loop runs from i = 0 to i <= str.length, which means i goes up to str.length (3). But string indices go from 0 to length-1 (2).Step 2: Identify out-of-bounds access
At i = 3, str[3] is undefined, causing freq[undefined] to be updated, which is incorrect.Final Answer:
Loop condition should be i < str.length, not i <= str.length -> Option DQuick Check:
Loop index must be less than length [OK]
- Using <= instead of < in loop condition
- Initializing freq as array instead of object
- Confusing for...in with for...of loops
"aabbc", which TypeScript code snippet correctly returns an object with only characters that appear exactly twice?Solution
Step 1: Count frequencies correctly
Loop through string, count each character's occurrences in freq object.Step 2: Filter characters with count exactly 2
Use Object.entries(freq) to get pairs, filter those with value 2, then convert back to object.Final Answer:
Code snippet that counts and filters for count === 2 -> Option AQuick Check:
Filter freq entries where value is 2 [OK]
- Filtering for count === 1 instead of 2
- Assigning fixed count 2 inside loop
- Returning keys instead of filtered object
Ready to prove it?
Pass the test and this pattern moves unknown
