Data Structures
Counter / Frequency Map
Add or update one count: O(1) · Build the full frequency map for n items: O(n) · Find the most common item: O(k), where k is the number of distinct items.
The idea, in plain English
A frequency map is like a tally chart at a school election. Instead of writing down every vote one by one, you keep a single running count next to each candidate's name. You bump the count up each time their name comes up. It's a hash map whose values always answer 'how many times have I seen this?' It's sometimes called a multiset, because it tracks duplicates without storing every single copy.
How it works
- 1Start with an empty map from item to count.
- 2Every time an item appears, look up its current count. If it's brand new, start at 0. Then add 1.
- 3To read: check any single item's count directly, or scan the whole map to find the item with the highest count.
When you'd use it
Use a frequency map for counting word frequency in text, finding the most common item in a list, checking if two words are anagrams (they have the same letter counts), or tracking how many times each event happened.
Common beginner mistakes
- Remember to default to 0 for an item you haven't seen yet. If you forget, the very first count crashes.
- Don't confuse 'the highest count' with 'the item that has it.' You want the key whose count is highest, not the count number itself.
Try it — edit and run
Click the code to edit · press ⌘/Ctrl+↵ to run
Editable code. Tab and Shift+Tab indent. Press Escape, then Tab, to move focus out of the editor.
i count: 4
s count: 4
p count: 2
Most common: i (4)See it in motion
Ready. Press play to tally letters into a map.
Not sure this is the right topic? See the learning paths → or where this leads →