Bird
Raised Fist0
DSA Typescriptprogramming~10 mins

Character Frequency Counting in DSA Typescript - 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?
Yes→Increase count by 1
↓
Update map
↓
Add character with count 1
↓
More characters?
Yes→Repeat
No↓
Return frequency map
Start with an empty map. For each character, add or update its count. Repeat until all characters are processed.
Execution Sample
DSA Typescript
function charFrequency(s: string): Record<string, number> {
  const freq: Record<string, number> = {};
  for (const ch of s) {
    freq[ch] = (freq[ch] || 0) + 1;
  }
  return freq;
}
Counts how many times each character appears in the input string.
Execution Table
StepOperationCharacterFrequency Map StateVisual State
1Initialize frequency map-{}{}
2Read character'a'{}{}
3Add 'a' with count 1a{'a':1}{a:1}
4Read character'b'{'a':1}{a:1}
5Add 'b' with count 1b{'a':1,'b':1}{a:1, b:1}
6Read character'a'{'a':1,'b':1}{a:1, b:1}
7Increment 'a' counta{'a':2,'b':1}{a:2, b:1}
8Read character'c'{'a':2,'b':1}{a:2, b:1}
9Add 'c' with count 1c{'a':2,'b':1,'c':1}{a:2, b:1, c:1}
10Read character'b'{'a':2,'b':1,'c':1}{a:2, b:1, c:1}
11Increment 'b' countb{'a':2,'b':2,'c':1}{a:2, b:2, c:1}
12Read character'a'{'a':2,'b':2,'c':1}{a:2, b:2, c:1}
13Increment 'a' counta{'a':3,'b':2,'c':1}{a:3, b:2, c:1}
14No more characters-{'a':3,'b':2,'c':1}{a:3, b:2, c:1}
💡 All characters processed, frequency map complete
Variable Tracker
VariableStartAfter Step 3After Step 5After Step 7After Step 9After Step 11After Step 13Final
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 add the character with count 1 when it is not in the map?
Because the character appears for the first time, so its count starts at 1. See execution_table step 3 where 'a' is added with count 1.
Why do we use (freq[ch] || 0) + 1 to update the count?
This means if freq[ch] is undefined (character not seen), use 0, then add 1. This avoids errors and correctly increments counts. See steps 7 and 11 where counts increase.
What happens if the input string is empty?
The loop never runs, so the frequency map stays empty. See execution_table step 1 and 14 where map is {} and no characters processed.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 7, what is the frequency of 'a'?
A1
B2
C3
D0
💡 Hint
Check the 'Frequency Map State' column at step 7 in execution_table
At which step does the character 'c' first appear in the frequency map?
AStep 8
BStep 10
CStep 9
DStep 11
💡 Hint
Look for when 'c' is added with count 1 in execution_table
If the input string was 'aaa', how would the frequency map change after step 3?
A{'a':1}
B{'a':3}
C{}
D{'a':2}
💡 Hint
After first character, count is 1; increments happen in later steps
Concept Snapshot
Character Frequency Counting:
- Use a map/dictionary to store counts
- For each character: if new, add with 1
- If seen, increment count
- Result is map of char -> frequency
- Useful for text analysis and counting
Full Transcript
This concept counts how many times each character appears in a string. We start with an empty map. For each character, we check if it is already in the map. If not, we add it with count 1. If yes, we increase its count by 1. We repeat this until all characters are processed. The final map shows the frequency of each character. For example, in the string 'abacba', 'a' appears 3 times, 'b' 2 times, and 'c' once. This method is simple and efficient for counting characters.

Practice

(1/5)
1. What does character frequency counting in a string help us find?
easy
A. How many times each character appears in the string
B. The length of the string
C. The first character of the string
D. The position of a character in the string

Solution

  1. Step 1: Understand character frequency counting

    Character frequency counting means counting how many times each character appears in a string.
  2. Step 2: Identify what it helps find

    This counting helps us know the number of occurrences of each character, not the length or position.
  3. Final Answer:

    How many times each character appears in the string -> Option A
  4. Quick Check:

    Frequency counting = character counts [OK]
Hint: Frequency counting means counting each character's occurrences [OK]
Common Mistakes:
  • Confusing frequency with string length
  • Thinking it finds character positions
  • Mixing frequency with first character only
2. Which TypeScript code snippet correctly initializes an empty object to store character frequencies?
easy
A. const freq = new Map();
B. const freq = {};
C. const freq = [];
D. const freq = '';

Solution

  1. 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 {}.
  2. 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.
  3. Final Answer:

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

    Empty object = {} [OK]
Hint: Use {} to start an empty object for frequency counts [OK]
Common Mistakes:
  • Using array [] instead of object {}
  • Using empty string '' instead of object
  • Confusing Map with plain object initialization
3. What is the output of this TypeScript code?
const str = 'hello';
const freq: {[key: string]: number} = {};
for (const ch of str) {
  freq[ch] = (freq[ch] || 0) + 1;
}
console.log(freq);
medium
A. {"h":1,"e":1,"l":3,"o":1}
B. {"h":1,"e":1,"l":1,"o":1}
C. {"h":1,"e":1,"l":2,"o":1}
D. {"h":0,"e":0,"l":0,"o":0}

Solution

  1. Step 1: Loop through each character and count

    Characters: 'h', 'e', 'l', 'l', 'o'. For each, increase count in freq object.
  2. Step 2: Calculate counts

    'h' = 1, 'e' = 1, 'l' = 2 (appears twice), 'o' = 1.
  3. Final Answer:

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

    Count 'l' twice = 2 [OK]
Hint: Add 1 or start at 0 for each char count [OK]
Common Mistakes:
  • Counting 'l' only once
  • Setting counts to zero
  • Miswriting object output format
4. Find the error in this TypeScript code for counting character frequency:
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);
medium
A. Use 'for...in' instead of 'for' loop
B. freq should be initialized as an array, not object
C. Missing declaration of variable ch
D. Loop condition should be i < str.length, not i <= str.length

Solution

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

    At i = 3, str[3] is undefined, causing freq[undefined] to be updated, which is incorrect.
  3. Final Answer:

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

    Loop index must be less than length [OK]
Hint: Use i < length to avoid out-of-bounds errors [OK]
Common Mistakes:
  • Using <= instead of < in loop condition
  • Initializing freq as array instead of object
  • Confusing for...in with for...of loops
5. Given the string "aabbc", which TypeScript code snippet correctly returns an object with only characters that appear exactly twice?
hard
A. const freq: {[key: string]: number} = {}; for (const ch of str) { freq[ch] = (freq[ch] || 0) + 1; } const result = Object.fromEntries(Object.entries(freq).filter(([k,v]) => v === 2));
B. const freq = new Map(); for (const ch of str) { freq.set(ch, (freq.get(ch) || 0) + 1); } const result = Object.fromEntries([...freq].filter(([k,v]) => v === 1));
C. const freq = {}; for (const ch of str) { freq[ch] = 2; } const result = freq;
D. const freq = {}; for (const ch of str) { freq[ch] = (freq[ch] || 0) + 1; } const result = Object.keys(freq);

Solution

  1. Step 1: Count frequencies correctly

    Loop through string, count each character's occurrences in freq object.
  2. 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.
  3. Final Answer:

    Code snippet that counts and filters for count === 2 -> Option A
  4. Quick Check:

    Filter freq entries where value is 2 [OK]
Hint: Filter entries with value === 2 after counting [OK]
Common Mistakes:
  • Filtering for count === 1 instead of 2
  • Assigning fixed count 2 inside loop
  • Returning keys instead of filtered object
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