Browse curriculum

Hash Map

The Hash Map Pattern

Remember what you have already seen so a later step can look it up in O(1) on average instead of rescanning. The everyday forms: look up a complement (Two Sum), count frequencies (Valid Anagram, Top K Frequent Elements), group items under a key they share (Group Anagrams), and test membership with a set when only presence matters (Longest Consecutive Sequence).

5

Interactive problems

1

Free to open

Recognise

How do you recognise a hash map problem?

The brute force is a nested loop whose inner loop asks "have I seen X before?", "how many times?" or "which items share this?" — a hash map answers each.

Complexity

What is the time complexity of the hash map pattern?

O(n) time on average for one pass with O(1) average lookups, paid for with O(n) extra space for the map — against O(n²) time and O(1) space for the nested loop.

Problems

Hash Map practice problems

Each problem pairs a worked explanation with an interactive visualizer you step through yourself, plus the implementation in JavaScript, Python, Java and C++.

Complexity

Hash Map problems by difficulty and complexity

The difficulty, running time and extra space of every hash map solution on this page, as each lesson derives them.

LessonDifficultyBestAverageWorstSpace
Two SumEasyΩ(1)Θ(n)O(n)O(n)
Valid AnagramEasyΩ(1)Θ(n)O(n)O(k)
Group AnagramsMediumΩ(n · k log k)Θ(n · k log k)O(n · k log k)O(n · k)
Top K Frequent ElementsMediumΩ(n)Θ(n)O(n)O(n)
Longest Consecutive SequenceMediumΩ(n)Θ(n)O(n)O(n)
Curriculum

The underlying technique is covered from first principles in the hash map lesson in the DSA visualizer curriculum. Hash Map is one of the 17 coding interview patterns, and its problems also appear in the DSA 75 interview sprint.

Directory

Every other coding interview pattern