Browse curriculum

Hash Map

Hash Map Interview Questions: 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). Below are the hash map interview questions from LeetCode, each with a step-by-step visual solution.

20

Interactive problems

2

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 interview questions: 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)
Contains DuplicateEasyΩ(1)Θ(n)O(n)O(n)
Find the Difference of Two ArraysEasyΩ(n + m)Θ(n + m)O(n + m)O(n + m)
Unique Number of OccurrencesEasyΩ(n)Θ(n)O(n)O(n)
Valid AnagramEasyΩ(1)Θ(n)O(n)O(k)
Longest PalindromeEasyΩ(n)Θ(n)O(n)O(1)
Determine if Two Strings Are CloseMediumΩ(1)Θ(n)O(n)O(1)
Equal Row and Column PairsMediumΩ(n²)Θ(n²)O(n²)O(n²)
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)
Valid SudokuMediumΩ(1)Θ(81)O(81)O(81)
Detect SquaresMediumΩ(1)Θ(p)O(p)O(p)
Majority ElementEasyΩ(n)Θ(n)O(n)O(1)
Majority Element IIMediumΩ(n)Θ(n)O(n)O(1)
Isomorphic StringsEasyΩ(1)Θ(n)O(n)O(k)
Word PatternEasyΩ(m)Θ(n + m)O(n + m)O(n + m)
Ransom NoteEasyΩ(m)Θ(m + n)O(m + n)O(1)
First Unique Character in a StringEasyΩ(n)Θ(n)O(n)O(1)
Roman to IntegerEasyΩ(n)Θ(n)O(n)O(1)
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 18 coding interview patterns, and its problems also appear in the DSA 75 interview sprint.

Directory

Every other coding interview pattern