📖 Scenario: You work at a bookstore. You want to count how many times each book title appears in a list of sold books to understand which books are popular.
🎯 Goal: Build a program that counts the frequency of each book title sold using a hash map (dictionary) and displays the counts.
📋 What You'll Learn
Create a dictionary to store book titles and their counts
Add a list of sold book titles
Use a loop to count how many times each book title appears
Print the frequency of each book title
💡 Why This Matters
🌍 Real World
Counting frequencies of items is useful in sales analysis, inventory management, and data summarization.
💼 Career
Understanding how to use hash maps (dictionaries) to count frequencies is a common task in software development, data analysis, and backend programming.
Progress0 / 4 steps
1
Create the list of sold book titles
Create a list of strings called soldBooks with these exact titles: "The Alchemist", "1984", "The Alchemist", "Brave New World", "1984"
DSA C#
Hint
Use List<string> and initialize it with the exact book titles inside curly braces.
2
Create the dictionary to count frequencies
Create a dictionary called bookCounts that maps strings to integers to store the count of each book title.
DSA C#
Hint
Use Dictionary<string, int> to create bookCounts.
3
Count the frequency of each book title
Use a foreach loop with variable book to iterate over soldBooks. Inside the loop, if book is already a key in bookCounts, increase its value by 1. Otherwise, add book to bookCounts with value 1.
DSA C#
Hint
Use ContainsKey to check if the book is already counted.
4
Print the frequency of each book title
Use a foreach loop with variables title and count to iterate over bookCounts. Inside the loop, print the book title and its count in the format: "{title}: {count}".
DSA C#
Hint
Use foreach (KeyValuePair<string, int> entry in bookCounts) and Console.WriteLine with string interpolation.
Practice
(1/5)
1. What is the main purpose of using a frequency counter pattern with a hash map in algorithms?
easy
A. To count how many times each element appears in a collection
B. To sort elements in ascending order
C. To reverse the order of elements
D. To find the maximum value in a list
Solution
Step 1: Understand frequency counter pattern
The frequency counter pattern uses a hash map to store counts of each element in a collection.
Step 2: Identify the purpose
This pattern helps to quickly find how many times each element appears, which is useful for comparisons or validations.
Final Answer:
To count how many times each element appears in a collection -> Option A
Quick Check:
Frequency counter = count elements [OK]
Hint: Frequency counter counts occurrences using a hash map [OK]
Common Mistakes:
Confusing frequency counting with sorting
Thinking it reverses elements
Assuming it finds max value
2. Which of the following C# code snippets correctly initializes a frequency counter using a Dictionary for integers?
easy
A. var freq = new HashSet<int>();
B. var freq = new List<int>();
C. var freq = new Dictionary();
D. var freq = new int[10];
Solution
Step 1: Identify correct data structure for frequency counting
A Dictionary maps each integer to its count, perfect for frequency counting.
Step 2: Check other options
List<int> stores values but not counts, HashSet<int> stores unique values without counts, int[] is fixed size and less flexible.
Final Answer:
var freq = new Dictionary(); -> Option C
Quick Check:
Dictionary for frequency map [OK]
Hint: Use Dictionary to map element to count [OK]
Common Mistakes:
Using List instead of Dictionary for counts
Using HashSet which stores only unique elements
Using fixed-size array without mapping keys
3. What will be the output of the following C# code?
var arr = new int[] {1, 2, 2, 3, 3, 3};
var freq = new Dictionary();
foreach (var num in arr) {
if (freq.ContainsKey(num)) freq[num]++;
else freq[num] = 1;
}
foreach (var kvp in freq) {
Console.Write(kvp.Key + ":" + kvp.Value + " ");
}
medium
A. 3:3 2:2 1:1
B. 1:1 2:2 3:3
C. 1:1 2:1 3:1
D. 1:3 2:2 3:1
Solution
Step 1: Count frequencies in array
1 appears once, 2 appears twice, 3 appears three times.
Step 2: Output order in Dictionary foreach
Dictionary preserves insertion order in recent C# versions, so output is 1:1 2:2 3:3.
Final Answer:
1:1 2:2 3:3 -> Option B
Quick Check:
Count each element correctly [OK]
Hint: Count each element, print in insertion order [OK]
Common Mistakes:
Mixing counts of elements
Assuming Dictionary outputs sorted keys
Forgetting to increment counts
4. Identify the error in the following C# code that tries to count character frequencies in a string:
string text = "hello";
var freq = new Dictionary();
foreach (char c in text) {
freq[c] += 1;
}
medium
A. Trying to increment a key that may not exist causes a KeyNotFoundException
B. The dictionary is not initialized
C. The foreach loop syntax is incorrect
D. Characters cannot be used as dictionary keys
Solution
Step 1: Analyze dictionary usage
freq[c] += 1 assumes key c exists, but keys are not added before incrementing.
Step 2: Identify exception cause
Accessing freq[c] when c is not a key throws KeyNotFoundException.
Final Answer:
Trying to increment a key that may not exist causes a KeyNotFoundException -> Option A
Quick Check:
Increment without key check causes error [OK]
Hint: Check key exists before incrementing frequency [OK]
Common Mistakes:
Assuming keys auto-initialize in Dictionary
Ignoring exception on missing keys
Misunderstanding foreach syntax
5. Given two integer arrays arr1 and arr2, which C# code snippet correctly uses the frequency counter pattern to check if arr2 contains the squares of all elements in arr1 with matching frequencies?
hard
A. var freq1 = new Dictionary();
var freq2 = new Dictionary();
foreach(var num in arr1) freq1[num * num] = freq1.GetValueOrDefault(num * num,0) + 1;
foreach(var num in arr2) freq2[num] = freq2.GetValueOrDefault(num,0) + 1;
return freq1.SequenceEqual(freq2);
B. var freq1 = new Dictionary();
foreach(var num in arr1) freq1[num * num] = freq1.GetValueOrDefault(num * num,0) + 1;
foreach(var num in arr2) { if(!freq1.ContainsKey(num)) return false; freq1[num]--; } return freq1.Values.All(v => v == 0);
C. var freq1 = new Dictionary();
var freq2 = new Dictionary();
foreach(var num in arr1) freq1[num] = freq1.GetValueOrDefault(num,0) + 1;
foreach(var num in arr2) freq2[num * num] = freq2.GetValueOrDefault(num * num,0) + 1;
return freq1.SequenceEqual(freq2);
D. var freq1 = new Dictionary();
var freq2 = new Dictionary();
foreach(var num in arr1) freq1[num] = freq1.GetValueOrDefault(num,0) + 1;
foreach(var num in arr2) freq2[num] = freq2.GetValueOrDefault(num,0) + 1;
foreach(var kvp in freq1) { if(!freq2.ContainsKey(kvp.Key * kvp.Key) || freq2[kvp.Key * kvp.Key] != kvp.Value) return false; } return true;
Solution
Step 1: Build frequency maps for arr1 and arr2
freq1 counts elements in arr1, freq2 counts elements in arr2.
Step 2: Check if freq2 has squares of freq1 keys with matching counts
For each key in freq1, check if freq2 contains key squared with same frequency.
Final Answer:
Code snippet C correctly implements the frequency counter pattern for this problem -> Option D
Quick Check:
Compare freq1 keys squared with freq2 frequencies [OK]