Bird
Raised Fist0
DSA Javascriptprogramming~10 mins

Character Frequency Counting in DSA Javascript - Execution Trace

Choose your learning style10 modes available
Concept Flow - Character Frequency Counting
Start with empty frequency map
↓
Read next character from string
↓
Is character in map?
No→Add character with count 1
|Yes↓
Increment character count by 1
↓
More characters?
Yes→Read next character
No↓
Return frequency map
We start with an empty map, read each character, add or update its count, and finally return the map.
Execution Sample
DSA Javascript
function charFrequency(str) {
  const freq = {};
  for (const ch of str) {
    freq[ch] = (freq[ch] || 0) + 1;
  }
  return freq;
}
Counts how many times each character appears in the input string.
Execution Table
StepOperationCharacterFrequency Map StateAction Taken
1Initialize frequency map-{}Create empty map
2Read charactera{}Add 'a':1
3Read characterb{'a':1}Add 'b':1
4Read charactera{'a':1,'b':1}Increment 'a' to 2
5Read characterc{'a':2,'b':1}Add 'c':1
6Read characterb{'a':2,'b':1,'c':1}Increment 'b' to 2
7Read charactera{'a':2,'b':2,'c':1}Increment 'a' to 3
8End of string-{'a':3,'b':2,'c':1}Return frequency map
💡 All characters processed, frequency map complete
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4After Step 5After Step 6After Step 7Final
freq{}{'a':1}{'a':1,'b':1}{'a':2,'b':1}{'a':2,'b':1,'c':1}{'a':2,'b':2,'c':1}{'a':3,'b':2,'c':1}{'a':3,'b':2,'c':1}
ch-abacba-
Key Moments - 3 Insights
Why do we use freq[ch] = (freq[ch] || 0) + 1 instead of just freq[ch] + 1?
Because freq[ch] might be undefined the first time we see the character. Using (freq[ch] || 0) ensures we start counting from 0. See steps 2 and 3 in execution_table where characters are added first.
What happens if the input string is empty?
The loop never runs, so the frequency map stays empty as shown in step 1 and step 8 of execution_table.
Why do we return the frequency map after processing all characters?
Because only after counting all characters do we have the complete frequency data. Step 8 shows returning the final map.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the frequency map after reading the third character?
A{'a':1,'b':2}
B{'a':1,'b':1}
C{'a':2,'b':1}
D{'a':3,'b':1}
💡 Hint
Check row 4 in execution_table where the third character 'a' increments count to 2
At which step does the character 'c' first appear in the frequency map?
AStep 5
BStep 3
CStep 6
DStep 7
💡 Hint
Look at execution_table row 5 where 'c' is added with count 1
If the input string was empty, what would be the final frequency map?
Aundefined
B{}
C{'a':1}
Dnull
💡 Hint
Refer to key_moments question 2 and execution_table steps 1 and 8
Concept Snapshot
Character Frequency Counting:
- Use a map/object to store counts
- For each character: add or increment count
- Use freq[ch] = (freq[ch] || 0) + 1 to handle new chars
- Return map after processing all characters
- Works for any string input
Full Transcript
This concept counts how many times each character appears in a string. We start with an empty frequency map. For each character, we check if it exists in the map. If not, we add it with count 1. If yes, we increase its count by 1. After processing all characters, we return the frequency map. This method handles empty strings by returning an empty map. The key trick is using (freq[ch] || 0) + 1 to handle characters not yet in the map.

Practice

(1/5)
1. What does character frequency counting mean in simple terms?
easy
A. Sorting characters alphabetically
B. Counting how many times each character appears in a string
C. Replacing characters with numbers
D. Removing duplicate characters from a string

Solution

  1. Step 1: Understand the meaning of frequency

    Frequency means how often something appears.
  2. Step 2: Apply to characters in a string

    Counting frequency means counting how many times each character shows up in the string.
  3. Final Answer:

    Counting how many times each character appears in a string -> Option B
  4. Quick Check:

    Frequency counting = Counting characters [OK]
Hint: Frequency means count occurrences of each character [OK]
Common Mistakes:
  • Confusing frequency with sorting
  • Thinking frequency means removing duplicates
  • Mixing frequency with character replacement
2. Which of the following JavaScript code snippets correctly initializes an empty object to store character frequencies?
easy
A. const freq = '';
B. const freq = [];
C. const freq = {};
D. const freq = null;

Solution

  1. Step 1: Identify the data structure for frequency counting

    We use an object to store characters as keys and counts as values.
  2. Step 2: Check correct syntax for empty object

    Empty object is created with curly braces {} in JavaScript.
  3. Final Answer:

    const freq = {}; -> Option C
  4. Quick Check:

    Empty object = {} [OK]
Hint: Use curly braces {} to create empty object [OK]
Common Mistakes:
  • Using array [] instead of object {}
  • Using empty string '' instead of object
  • Assigning null which is not an object
3. What will be the output of the following code?
const str = 'hello';
const freq = {};
for (const ch of str) {
  freq[ch] = (freq[ch] || 0) + 1;
}
console.log(freq);
medium
A. {"h":1,"e":1,"l":2,"o":1}
B. {"h":1,"e":1,"l":1,"o":1}
C. {"h":0,"e":0,"l":0,"o":0}
D. SyntaxError

Solution

  1. Step 1: Loop through each character in 'hello'

    Characters are 'h', 'e', 'l', 'l', 'o'.
  2. 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.
  3. Final Answer:

    {"h":1,"e":1,"l":2,"o":1} -> Option A
  4. Quick Check:

    Count 'l' twice, others once [OK]
Hint: Use freq[ch] = (freq[ch] || 0) + 1 to count [OK]
Common Mistakes:
  • Counting 'l' only once
  • Getting syntax error from code
  • Confusing keys and values in output
4. Find the error in this code that counts character frequency:
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);
medium
A. Loop condition should be i < str.length, not i <= str.length
B. freq should be initialized as an array, not object
C. Use let instead of const for freq
D. Missing semicolon after freq[ch] assignment

Solution

  1. 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').
  2. Step 2: Identify out-of-bounds access

    str[3] is undefined, so freq[undefined] is updated causing wrong key.
  3. Final Answer:

    Loop condition should be i < str.length, not i <= str.length -> Option A
  4. Quick Check:

    Array index max is length - 1 [OK]
Hint: Use i < length to avoid out-of-bounds errors [OK]
Common Mistakes:
  • Using <= instead of < in loop
  • Initializing freq as array instead of object
  • Ignoring undefined character access
5. Given the string "aabbccddeeffgghhii", which code snippet correctly counts only characters that appear more than once and stores them in freq object?
hard
A. const freq = {}; for (const ch of str) { freq[ch] = (freq[ch] || 0) + 1; } const filtered = {}; for (const ch in freq) { if (freq[ch] > 1) filtered[ch] = freq[ch]; }
B. const freq = {}; for (const ch of str) { if (freq[ch]) freq[ch]++; else freq[ch] = 1; } for (const ch in freq) { if (freq[ch] < 2) freq[ch] = 0; }
C. const freq = {}; for (const ch of str) { freq[ch] = 1; } for (const ch in freq) { if (freq[ch] > 1) delete freq[ch]; }
D. const freq = {}; for (const ch of str) { freq[ch] = (freq[ch] || 0) + 1; } for (const ch in freq) { if (freq[ch] <= 1) delete freq[ch]; }

Solution

  1. Step 1: Count all character frequencies

    Use freq[ch] = (freq[ch] || 0) + 1 to count all characters.
  2. Step 2: Delete characters with frequency <= 1 from freq

    Iterate and delete keys where freq[ch] <= 1 to leave only duplicates in freq.
  3. Final Answer:

    Code snippet that counts all then deletes singles from freq -> Option D
  4. Quick Check:

    Delete freq <= 1 from freq [OK]
Hint: Count all, then delete characters with count <= 1 [OK]
Common Mistakes:
  • Deleting keys while iterating freq object
  • Setting frequency to 0 instead of removing
  • Overwriting counts incorrectly
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard