Character Frequency Counting in DSA Javascript - Time & Space Complexity
Counting how often each character appears in a string is a common task. Understanding how the time needed grows with the string length helps us write efficient code.
We want to know: how does the work increase as the string gets longer?
Analyze the time complexity of the following code snippet.
const countChars = (str) => {
const freq = {};
for (let i = 0; i < str.length; i++) {
const char = str[i];
freq[char] = (freq[char] || 0) + 1;
}
return freq;
};
This code counts how many times each character appears in the input string.
Identify the loops, recursion, array traversals that repeat.
- 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 code checks each character once, so the work grows directly with the string size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks and updates |
| 100 | About 100 checks and updates |
| 1000 | About 1000 checks and updates |
Pattern observation: The number of operations grows in a straight line with input size.
Time Complexity: O(n)
This means the time to count characters grows directly in proportion to the string length.
[X] Wrong: "Since we update counts inside the loop, it might be slower than linear time."
[OK] Correct: Each update is a simple operation done once per character, so it does not add extra loops or nested work.
Knowing how to analyze simple loops like this builds your confidence for more complex problems. It shows you understand how work grows with input size, a key skill in interviews.
"What if we counted characters using nested loops to compare each character with every other? How would the time complexity change?"
Practice
Solution
Step 1: Understand the meaning of frequency
Frequency means how often something appears.Step 2: Apply to characters in a string
Counting frequency means counting how many times each character shows up in the string.Final Answer:
Counting how many times each character appears in a string -> Option BQuick Check:
Frequency counting = Counting characters [OK]
- Confusing frequency with sorting
- Thinking frequency means removing duplicates
- Mixing frequency with character replacement
Solution
Step 1: Identify the data structure for frequency counting
We use an object to store characters as keys and counts as values.Step 2: Check correct syntax for empty object
Empty object is created with curly braces {} in JavaScript.Final Answer:
const freq = {}; -> Option CQuick Check:
Empty object = {} [OK]
- Using array [] instead of object {}
- Using empty string '' instead of object
- Assigning null which is not an object
const str = 'hello';
const freq = {};
for (const ch of str) {
freq[ch] = (freq[ch] || 0) + 1;
}
console.log(freq);Solution
Step 1: Loop through each character in 'hello'
Characters are 'h', 'e', 'l', 'l', 'o'.Step 2: Count frequency using freq[ch] = (freq[ch] || 0) + 1
For each character, add 1 to its count or start at 1 if not present.Final Answer:
{"h":1,"e":1,"l":2,"o":1} -> Option AQuick Check:
Count 'l' twice, others once [OK]
- Counting 'l' only once
- Getting syntax error from code
- Confusing keys and values in output
const str = 'abc';
const freq = {};
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 range
Loop runs from i = 0 to i <= str.length, which means i goes up to str.length (3 for 'abc').Step 2: Identify out-of-bounds access
str[3] is undefined, so freq[undefined] is updated causing wrong key.Final Answer:
Loop condition should be i < str.length, not i <= str.length -> Option AQuick Check:
Array index max is length - 1 [OK]
- Using <= instead of < in loop
- Initializing freq as array instead of object
- Ignoring undefined character access
"aabbccddeeffgghhii", which code snippet correctly counts only characters that appear more than once and stores them in freq object?Solution
Step 1: Count all character frequencies
Use freq[ch] = (freq[ch] || 0) + 1 to count all characters.Step 2: Delete characters with frequency <= 1 from freq
Iterate and delete keys where freq[ch] <= 1 to leave only duplicates in freq.Final Answer:
Code snippet that counts all then deletes singles from freq -> Option DQuick Check:
Delete freq <= 1 from freq [OK]
- Deleting keys while iterating freq object
- Setting frequency to 0 instead of removing
- Overwriting counts incorrectly
Ready to prove it?
Pass the test and this pattern moves unknown
