💡
Exercise 9

Frequency Counter — Counting Like a Pro 10 XP Easy

Ctrl+Enter Run Ctrl+S Save

You just crushed Contains Duplicate — nice! 🎉 Now let's level up the dictionary (hash map) skill that powers a TON of array problems.

Picture this: it's election day at school. Votes are coming in one by one — "Alice", "Bob", "Alice", "Bob", "Charlie", "Bob". How do you count who's winning? You grab a piece of paper and make tally marks next to each name. That paper? That's a dictionary. 🗳️

The Frequency Counter Pattern:

  • Create an empty dictionary — your tally sheet.
  • Walk through the array one element at a time.
  • For each element: if it's already in the dictionary, add 1 to its count. If not, start it at 1.
  • When you're done, the dictionary holds the exact count of every element. Magic! ✨

Here's the pattern visualized:

# Array: [1, 2, 1, 3, 1, 2] # Step 1: see 1 → freq = {1: 1} # Step 2: see 2 → freq = {1: 1, 2: 1} # Step 3: see 1 → freq = {1: 2, 2: 1} # Step 4: see 3 → freq = {1: 2, 2: 1, 3: 1} # Step 5: see 1 → freq = {1: 3, 2: 1, 3: 1} # Step 6: see 2 → freq = {1: 3, 2: 2, 3: 1}

The slick Python trick is dict.get(key, 0) — it returns the current count if the key exists, or 0 if it doesn't. Then just add 1. No messy if/else needed!

freq[item] = freq.get(item, 0) + 1 # One beautiful line 🧑‍🍳

⏱ Time Complexity: O(n) — One pass through the array. Each dictionary lookup/insert is O(1) on average.

💾 Space Complexity: O(n) — In the worst case, every element is unique, so the dictionary has n entries.

Why does this matter? Because the Two Sum problem coming up next uses a dictionary for lookups — but the pattern of "build a dict in one pass" starts right here. Master counting first, then lookups become second nature. 🧠

📋 Instructions
Write a function `count_frequency(arr)` that returns a dictionary where: - **Keys** are the elements from the array. - **Values** are how many times each element appears. Then test it: ```python print(count_frequency([1, 2, 1, 3, 1, 2])) print(count_frequency(['a', 'b', 'a', 'b', 'c', 'b'])) freq = count_frequency(['a', 'b', 'a', 'b', 'c', 'b']) most = max(freq, key=freq.get) print(f"Most frequent: {most} ({freq[most]} times)") ```
Create an empty dictionary: freq = {}. Then loop through each item in the array and do freq[item] = freq.get(item, 0) + 1. The .get(item, 0) gives you the current count (or 0 if new), then you add 1!
⚠️ Try solving it yourself first — you'll learn more!
def count_frequency(arr):
    freq = {}
    for item in arr:
        freq[item] = freq.get(item, 0) + 1
    return freq

print(count_frequency([1, 2, 1, 3, 1, 2]))
print(count_frequency(['a', 'b', 'a', 'b', 'c', 'b']))
freq = count_frequency(['a', 'b', 'a', 'b', 'c', 'b'])
most = max(freq, key=freq.get)
print(f"Most frequent: {most} ({freq[most]} times)")
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.