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.
Interactive problems
Free to open
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.
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.
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++.
- Two SumFree
- Contains DuplicatePro
- Find the Difference of Two ArraysPro
- Unique Number of OccurrencesPro
- Valid AnagramPro
- Longest PalindromeFree
- Determine if Two Strings Are ClosePro
- Equal Row and Column PairsPro
- Group AnagramsPro
- Top K Frequent ElementsPro
- Longest Consecutive SequencePro
- Valid SudokuPro
- Detect SquaresPro
- Majority ElementPro
- Majority Element IIPro
- Isomorphic StringsPro
- Word PatternPro
- Ransom NotePro
- First Unique Character in a StringPro
- Roman to IntegerPro
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.
| Lesson | Difficulty | Best | Average | Worst | Space |
|---|---|---|---|---|---|
| Two Sum | Easy | Ω(1) | Θ(n) | O(n) | O(n) |
| Contains Duplicate | Easy | Ω(1) | Θ(n) | O(n) | O(n) |
| Find the Difference of Two Arrays | Easy | Ω(n + m) | Θ(n + m) | O(n + m) | O(n + m) |
| Unique Number of Occurrences | Easy | Ω(n) | Θ(n) | O(n) | O(n) |
| Valid Anagram | Easy | Ω(1) | Θ(n) | O(n) | O(k) |
| Longest Palindrome | Easy | Ω(n) | Θ(n) | O(n) | O(1) |
| Determine if Two Strings Are Close | Medium | Ω(1) | Θ(n) | O(n) | O(1) |
| Equal Row and Column Pairs | Medium | Ω(n²) | Θ(n²) | O(n²) | O(n²) |
| Group Anagrams | Medium | Ω(n · k log k) | Θ(n · k log k) | O(n · k log k) | O(n · k) |
| Top K Frequent Elements | Medium | Ω(n) | Θ(n) | O(n) | O(n) |
| Longest Consecutive Sequence | Medium | Ω(n) | Θ(n) | O(n) | O(n) |
| Valid Sudoku | Medium | Ω(1) | Θ(81) | O(81) | O(81) |
| Detect Squares | Medium | Ω(1) | Θ(p) | O(p) | O(p) |
| Majority Element | Easy | Ω(n) | Θ(n) | O(n) | O(1) |
| Majority Element II | Medium | Ω(n) | Θ(n) | O(n) | O(1) |
| Isomorphic Strings | Easy | Ω(1) | Θ(n) | O(n) | O(k) |
| Word Pattern | Easy | Ω(m) | Θ(n + m) | O(n + m) | O(n + m) |
| Ransom Note | Easy | Ω(m) | Θ(m + n) | O(m + n) | O(1) |
| First Unique Character in a String | Easy | Ω(n) | Θ(n) | O(n) | O(1) |
| Roman to Integer | Easy | Ω(n) | Θ(n) | O(n) | O(1) |
Related patterns and concepts
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.
Every other coding interview pattern
Two Pointers · 37 lessons
- Introduction to Two PointersFree
- Reverse String
- Reverse Vowels of a String
- Reverse Words in a String
- Two Sum II - Input Array Is SortedFree
- Max Number of K-Sum Pairs
- Valid Palindrome
- Merge Strings Alternately
- Greatest Common Divisor of Strings
- Merge Sorted Array
- Remove Duplicates from Sorted Array
- String Compression
- Remove Element
- Rotate Array
- Next Permutation
- Repeated String Match
- Find the Index of the First Occurrence in a StringFree
- Shortest Palindrome
- Squares of a Sorted Array
- Is Subsequence
- Valid Palindrome II
- Longest Palindromic Substring
- Palindromic Substrings
- Encode and Decode Strings
- Container With Most Water
- 3-Sum
- 3Sum Closest
- 4Sum
- Valid Triangle Number
- Move Zeroes
- Sort Colors
- Trapping Rain Water
- Multiply Strings
- String to Integer (atoi)
- Add Binary
- Add Strings
- Plus One
Sliding Window · 21 lessons
- Introduction to Sliding WindowFree
- Maximum Number of Vowels in a Substring of Given Length
- Longest Subarray of 1's After Deleting One Element
- Longest Substring Without Repeating CharactersFree
- Longest Repeating Character Replacement
- Minimum Window Substring
- Minimum Size Subarray Sum
- Max Consecutive Ones III
- Binary Subarrays With Sum
- Count Number of Nice Subarrays
- Number of Substrings Containing All Three Characters
- Fruit Into Baskets
- Longest Substring with At Most K Distinct Characters
- Number of Recent Calls
- Contains Duplicate II
- Fixed-Length Sliding Window
- Maximum Points You Can Obtain from Cards
- Maximum Sum of Distinct Subarrays With Length K
- Permutation in String
- Find All Anagrams in a String
- Sliding Window Maximum
Linked List · 23 lessons
- Linked List OverviewFree
- Reverse Linked ListFree
- Middle of the Linked ListFree
- Delete the Middle Node of a Linked List
- Odd Even Linked List
- Maximum Twin Sum of a Linked List
- Intersection of Two Linked ListsFree
- Merge Two Sorted ListsFree
- Add Two NumbersFree
- Linked List CycleFree
- Linked List Cycle IIFree
- Sort ListFree
- Rotate ListFree
- Palindrome Linked ListFree
- Remove Nth Node From End of ListFree
- Reorder ListFree
- Swap Nodes in PairsFree
- LRU CacheFree
- LFU Cache
- Find the Duplicate NumberFree
- Copy List with Random PointerFree
- Reverse Nodes in k-GroupFree
- Happy NumberFree
Stack · 24 lessons
- Stack OverviewFree
- Valid ParenthesesFree
- Decode String
- Longest Valid Parentheses
- Monotonic Stack Pattern
- Daily Temperatures
- Largest Rectangle in Histogram
- Maximal Rectangle
- Evaluate Reverse Polish Notation
- Min Stack
- Implement Queue using StacksFree
- Car Fleet
- Next Greater Element I
- Next Greater Element II
- Asteroid Collision
- Online Stock Span
- Sum of Subarray Minimums
- Sum of Subarray Ranges
- Remove K Digits
- Simplify Path
- Basic Calculator II
- Basic Calculator
- Removing Stars From a String
- Remove All Adjacent Duplicates in String
Binary Search · 20 lessons
- Binary SearchFree
- Search Insert Position
- First Bad Version
- Guess Number Higher or Lower
- Successful Pairs of Spells and Potions
- Search Suggestions System
- Single Element in a Sorted Array
- Sqrt(x)
- Valid Perfect Square
- Find Peak Element
- Find a Peak Element II
- Koko Eating Bananas (Apple Harvest)
- Split Array Largest Sum
- Search in Rotated Sorted Array
- Search in Rotated Sorted Array II
- Find Minimum in Rotated Sorted Array
- Search a 2D Matrix
- Search a 2D Matrix II
- Time Based Key-Value Store
- Median of Two Sorted Arrays
Heap / Priority Queue · 16 lessons
- Heap OverviewFree
- Kth Largest Element in an Array
- Smallest Number in Infinite Set
- Maximum Subsequence Score
- Total Cost to Hire K Workers
- Kth Largest Element in a StreamFree
- K Closest Points to Origin
- Find K Closest Elements
- Merge K Sorted Lists
- Design Twitter
- Kth Smallest Element in a Sorted Matrix
- Find Median from Data Stream
- Last Stone Weight
- Network Delay Time
- Min Cost to Connect All Points
- Swim in Rising Water
Depth-First Search · 46 lessons
- Introduction to DFSFree
- DFS FundamentalsFree
- Return Values in DFS
- Invert Binary Tree
- Maximum Depth of Binary Tree
- Same Tree
- Leaf-Similar Trees
- Balanced Binary Tree
- Subtree of Another Tree
- Path Sum
- Passing Values Down (State)
- Validate Binary Search Tree
- Kth Smallest Element in a BST
- Delete Node in a BST
- Search in a Binary Search Tree
- Insert into a Binary Search Tree
- Inorder Successor in BST
- Largest BST Subtree
- Vertical Order Traversal of a Binary Tree
- Recover Binary Search Tree
- Construct Binary Search Tree from Preorder Traversal
- Construct Binary Tree from Preorder and Inorder Traversal
- Serialize and Deserialize Binary Tree
- Binary Tree Tilt
- Diameter of Binary Tree
- Lowest Common Ancestor of a Binary Tree
- Path Sum II
- Path Sum III
- Longest ZigZag Path in a Binary Tree
- Count Good Nodes in Binary Tree
- Longest Univalue Path
- Graphs Overview
- Graph Representation: Adjacency List
- Clone Graph
- Graph Valid Tree
- Matrices as Graphs
- Flood Fill
- Types of DFS (Tree Traversals)
- Binary Tree Inorder TraversalFree
- Two Sum IV - Input is a BSTFree
- Number of Islands
- Making A Large Island
- Number of Distinct Islands
- Surrounded Regions
- Pacific Atlantic Water FlowFree
- Longest Increasing Path in a Matrix
Breadth-First Search · 18 lessons
- Introduction to BFSFree
- BFS OverviewFree
- Maximum Level Sum of a Binary Tree
- Binary Tree Level Order Traversal
- Symmetric Tree
- Binary Tree Right Side View
- Binary Tree Zigzag Level Order Traversal
- Maximum Width of Binary Tree
- All Nodes Distance K in Binary Tree
- Graphs OverviewFree
- Minimum Knight Moves
- Rotting Oranges
- Nearest Exit from Entrance in Maze
- Walls and Gates
- 01 Matrix
- Bus Routes
- Word Ladder
- Cheapest Flights Within K Stops
Backtracking · 17 lessons
- Introduction to BacktrackingFree
- Solution Space Trees
- Subsets (Power Set)
- Permutations
- Permutations II
- Combinations
- Letter Case Permutation
- N-Queens
- Sudoku Solver
- Subsets II
- Combination Sum
- Combination Sum II
- Combination Sum III
- Generate Parentheses
- Word Search
- Letter Combinations of a Phone Number
- Palindrome Partitioning
Graphs (Topological Sort) · 16 lessons
- Ordering Dependencies (Topological Sort)Free
- Course Schedule
- Course Schedule II
- Minimum Height Trees
- Alien Dictionary
- Redundant Connection
- Accounts Merge
- Critical Connections in a Network
- Keys and Rooms
- Number of Provinces
- Reorder Routes to Make All Paths Lead to the City Zero
- Evaluate Division
- Is Graph Bipartite?
- Number of Operations to Make Network Connected
- Path With Minimum Effort
- Reconstruct Itinerary
Dynamic Programming · 41 lessons
- Intro to Dynamic ProgrammingFree
- Solving a Question with DPFree
- Fibonacci Number
- N-th Tribonacci Number
- Domino and Tromino Tiling
- Counting Bits
- Pascal's Triangle
- Min Cost Climbing Stairs
- House Robber
- House Robber II
- House Robber III
- Coin Change
- Coin Change II
- Maximum Product Subarray
- Combination Sum IV
- Partition Equal Subset Sum
- Last Stone Weight II
- Target Sum
- Decode Ways
- Maximal Square
- Unique Paths
- Unique Paths II
- Minimum Path Sum
- Triangle
- Longest Common Subsequence
- Longest Palindromic Subsequence
- Palindrome Partitioning II
- Edit Distance
- Interleaving String
- Distinct Subsequences
- Regular Expression Matching
- Wildcard Matching
- Burst Balloons
- Best Time to Buy and Sell Stock with Cooldown
- Best Time to Buy and Sell Stock with Transaction Fee
- Best Time to Buy and Sell Stock III
- Best Time to Buy and Sell Stock IV
- Longest Increasing Subsequence
- Number of Longest Increasing Subsequence
- Word Break
- Maximum Profit in Job Scheduling
Greedy Algorithms · 17 lessons
- Introduction to Greedy AlgorithmsFree
- Kids With the Greatest Number of Candies
- Can Place Flowers
- Dota2 Senate
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock II
- Increasing Triplet Subsequence
- Gas Station
- Jump Game
- Jump Game II
- Task Scheduler
- Partition Labels
- Valid Parenthesis String
- Hand of Straights
- Merge Triplets to Form Target Triplet
- Integer to Roman
- Candy
