Challenge - 5 Problems
Character Frequency Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of Character Frequency Dictionary
What is the output of the following C# code that counts character frequencies in a string?
DSA C#
using System; using System.Collections.Generic; class Program { static void Main() { string input = "hello"; Dictionary<char, int> freq = new Dictionary<char, int>(); foreach (char c in input) { if (freq.ContainsKey(c)) { freq[c]++; } else { freq[c] = 1; } } foreach (var pair in freq) { Console.Write($"{pair.Key}:{pair.Value} "); } } }
Attempts:
2 left
💡 Hint
Count how many times each letter appears in "hello".
✗ Incorrect
The string "hello" has one 'h', one 'e', two 'l's, and one 'o'. The dictionary counts these frequencies correctly.
🧠 Conceptual
intermediateUnderstanding Frequency Counting Logic
Why do we check if the character key exists in the dictionary before incrementing its count?
Attempts:
2 left
💡 Hint
Think about what happens if you try to access a key that is not in the dictionary.
✗ Incorrect
If the key does not exist, trying to increment its value causes an error. Checking first allows adding the key with initial count 1.
🔧 Debug
advancedIdentify the Error in Frequency Counting Code
What error does the following code produce when run?
DSA C#
string input = "test"; Dictionary<char, int> freq = new Dictionary<char, int>(); foreach (char c in input) { freq[c] += 1; }
Attempts:
2 left
💡 Hint
What happens if you try to add 1 to a dictionary key that does not exist yet?
✗ Incorrect
The code tries to increment freq[c] without initializing freq[c], causing a KeyNotFoundException.
❓ Predict Output
advancedOutput After Filtering Characters
What is the output of this code that counts only alphabetic characters in the string?
DSA C#
using System; using System.Collections.Generic; class Program { static void Main() { string input = "a1b2a3"; Dictionary<char, int> freq = new Dictionary<char, int>(); foreach (char c in input) { if (Char.IsLetter(c)) { if (freq.ContainsKey(c)) { freq[c]++; } else { freq[c] = 1; } } } foreach (var pair in freq) { Console.Write($"{pair.Key}:{pair.Value} "); } } }
Attempts:
2 left
💡 Hint
Count only letters, ignore digits.
✗ Incorrect
Only 'a' and 'b' are letters. 'a' appears twice, 'b' once.
🧠 Conceptual
expertWhy Use Dictionary for Character Frequency Counting?
What is the main advantage of using a dictionary to count character frequencies in a string?
Attempts:
2 left
💡 Hint
Think about how quickly you can find and update counts for characters.
✗ Incorrect
Dictionaries provide quick access to keys, making frequency counting efficient.
