Hashing basics
Count first, answer afterwards. One pass stores how often each value appears, and every later question about counts takes a single look-up instead of another scan.
How to recognise it
- The question is about how often things appear (most frequent, least frequent, duplicates, "how many times").
- You would otherwise scan the whole array again for every value or every query.
- The values themselves can be large or negative, so you cannot simply use them as array indexes.
- Order does not matter, only which values appear and how many times.
The idea in one picture
Think of a tally sheet at the door of a party. Each guest who walks in adds a mark next to their name. When someone later asks "how many times did Sam come in?" you read one line instead of replaying the whole evening. Hashing is that tally sheet.
Counting happens in one pass. After that, every question about counts is a single look-up.
Two ways to keep the tally
| Values | Store | Example |
|---|---|---|
| Small, non-negative range (like 0 to 1000, or the 26 letters) | An array, count[value] | count[c - 'a']++ for letters |
| Large, negative or scattered | A hash map, value to count | HashMap in Java, unordered_map in C++, dict in Python |
An array is the fastest and simplest when it fits. A hash map gives average O(1) per operation for any values. The Reference page lists the exact calls in all three languages.
The template
count = empty map
for x in nums: # pass 1: count
count[x] = count[x] + 1 # missing keys start at 0
for each (value, times) in count: # pass 2: answer from the counts
use times to decide the answer
Most problems in this pattern differ only in the second pass.
A guided example: which value appears most often in [4, 4, 1, 1, 3]?
Before reading on: if two values tie, what should happen? The problem has to tell you. Here, the smaller value wins.
| After reading | count |
|---|---|
| 4 | 4 appears 1 time |
| 4, 4 | 4 appears 2 times |
| 4, 4, 1, 1 | 4 appears 2 times, 1 appears 2 times |
| 4, 4, 1, 1, 3 | 4 appears 2 times, 1 appears 2 times, 3 appears 1 time |
Now scan the counts and keep the best: 4 (2 times) beats nothing; 1 also has 2 times and is smaller, so it takes over; 3 (1 time) does not beat 2. The answer is 1.
Common mistakes
- Expecting a hash map to come back in insertion or sorted order. It does not, so tie rules must be written into your comparison.
- In C++, reading
count[x]to check a value, which silently insertsxwith count 0. Usecount.count(x)orfindto check without inserting. - Using an array counter when the values can be negative or as large as 10⁹.
- Counting inside a nested loop, which brings back the O(n²) work the counter was meant to remove.
Problems
- Highest Occurring Element in an Arrayeasyguide ready
- Second Highest Occurring Elementeasyguide ready
- Sum of Highest and Lowest Frequencyeasyguide ready