Ch. 18 · Data Structures & Algorithms

Hash Maps for Frequency and Membership Problems

Hash Maps for Frequency and Membership Problems. Learn the reasoning, a practical example, common mistakes and an interview exercise.

~2 min readbeginnerupdated Oct 3, 2026

Hash maps associate keys with counts or other summaries. They replace repeated searches with expected efficient lookup under suitable hashing.

Before you start

You should know arrays, loops and basic complexity notation. Start with a small input you can trace by hand. State what each variable means and which invariant is maintained, then use that invariant to explain correctness before discussing performance or writing a more compact solution.

The practical goal is to reason through this situation: Count occurrences once, then inspect whether an item repeats. Read the walkthrough first, then try the interview exercise before opening its answer. The important part is explaining the decision and its consequences, rather than remembering a definition alone.

Step-by-step walkthrough

Step 1: Build frequency information

Visit each value once to update its count.

Step 2: Preserve requested order

Scan the original sequence again for the first count-one value.

Step 3: State complexity assumptions

Expected hash lookup behavior supports expected linear processing.

Worked scenario

Count occurrences once, then inspect whether an item repeats.

For ‘swiss’, frequencies are s:3, w:1 and i:1. The second pass selects w because it appears before i. Iterating an arbitrarily ordered frequency structure would not necessarily preserve the problem’s definition of first. Space depends on the number of distinct keys.

Common mistake

Stating guaranteed constant lookup without assumptions oversimplifies hashing.

Verify the behavior

Test empty input, all duplicates and multiple unique candidates.

Interview exercise

Find the first unique character.

Answer and reasoning

Build frequencies, then traverse the original order to select the first count-one character.

Continue learning

Compare the scenario with the Data Structures and Algorithms interview questions and test your understanding with the Data Structures and Algorithms MCQs. For terminology and implementation details, consult the reference material.

More in Data Structures & Algorithms

read ✓Data Structures & Algorithms · mid

Bit Manipulation Patterns for Interviews

Set, test and clear bits, exploit XOR properties, and count set bits with the Brian Kernighan trick.

~2 min readread →
read ✓Data Structures & Algorithms · hard

Backtracking and Safe Pruning Rules

Backtracking and Safe Pruning Rules. Learn the reasoning, a practical example, common mistakes and an interview exercise.

~2 min readread →
read ✓Data Structures & Algorithms · easy

Big-O Complexity and Input Growth

Big-O Complexity and Input Growth. Learn the reasoning, a practical example, common mistakes and an interview exercise.

~2 min readread →
esc