Hash maps are one of the first tools we reach for in coding interviews. O(1) lookup sounds amazing... until it isn't.
The truth is, hash maps are not always the answer. Overusing them is a common mistake that costs interviews.
Senior engineers know not just when to use hash maps, but when to leave them in the toolbox. This guide shows you the 5 cases where hash maps fail and what to use instead.
Case 1: You Need Ordered Data
The problem
Hash maps don't maintain any order (or only maintain insertion order, not sorted order).
Example: "Find the kth smallest element" or "Find all elements between x and y"
Why hash maps fail
# Hash map doesn't help with ordering
nums = [5, 2, 8, 1, 9]
map = {num: True for num in nums}
# Can't efficiently find kth smallest or range [2, 5]What to use instead
Option 1: TreeMap/TreeSet (Java TreeMap, Python sortedcontainers)
from sortedcontainers import SortedList
nums = SortedList([5, 2, 8, 1, 9])
kth_smallest = nums[k-1] # O(1)
range_query = nums.irange(2, 5) # O(log n + m)Option 2: Sort the array
nums.sort() # O(n log n)
kth_smallest = nums[k-1]When to use:
- Need sorted iteration
- Range queries (elements between x and y)
- Kth smallest/largest
- Predecessor/successor queries
Case 2: You Need Range Queries
The problem
Hash maps can only look up exact keys, not ranges.
Example: "Count elements between 10 and 20" or "Sum of elements in range [i, j]"
Why hash maps fail
# Can't efficiently query ranges
map = {num: count for num, count in ...}
# To find elements in [10, 20], must check every key
result = [k for k in map if 10 <= k <= 20] # O(n)What to use instead
Option 1: Prefix sum (for sum queries)
prefix = [0]
for num in nums:
prefix.append(prefix[-1] + num)
# Sum from i to j in O(1)
range_sum = prefix[j+1] - prefix[i]Option 2: Segment tree (for updates + queries)
# Supports both updates and range queries in O(log n)Option 3: Binary search on sorted array
nums.sort()
left = bisect.bisect_left(nums, 10)
right = bisect.bisect_right(nums, 20)
elements_in_range = nums[left:right]When to use:
- Range sum queries → Prefix sum
- Range min/max queries → Segment tree
- Count in range → Binary search on sorted array
Case 3: Memory Is Severely Constrained
The problem
Hash maps use O(n) extra space. Sometimes you can't afford it.
Example: "Find duplicate in array where 1 ≤ nums[i] ≤ n" with O(1) space requirement
Why hash maps fail
# Uses O(n) space
seen = set()
for num in nums:
if num in seen:
return num
seen.add(num)What to use instead
Option 1: Two pointers (if sorted or can sort)
# Two Sum II with O(1) space
left, right = 0, len(nums) - 1
while left < right:
s = nums[left] + nums[right]
if s == target:
return [left+1, right+1]
elif s < target:
left += 1
else:
right -= 1Option 2: In-place marking (for specific constraints)
# Find duplicate where 1 ≤ nums[i] ≤ n
def findDuplicate(nums):
for num in nums:
index = abs(num) - 1
if nums[index] < 0:
return abs(num)
nums[index] = -nums[index]Option 3: Floyd's cycle detection (linked list problems)
# O(1) space for cycle detection
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return TrueWhen to use:
- Problem explicitly requires O(1) space
- Array has special properties (values in range [1, n])
- Can modify input array
Case 4: Dataset Is Very Small
The problem
Hash map overhead isn't worth it for tiny datasets.
Example: Counting lowercase English letters (only 26 possible)
Why hash maps are overkill
# Hash map for 26 letters - overkill
freq = {}
for char in s:
freq[char] = freq.get(char, 0) + 1What to use instead
Use array (direct indexing)
# Much simpler and faster
freq = [0] * 26
for char in s:
freq[ord(char) - ord('a')] += 1When to use:
- Small fixed alphabet (a-z, 0-9)
- Known small range (e.g., ages 0-120)
- Values are small integers
Benefits:
- Simpler code
- Faster (no hashing)
- Less memory overhead
- O(1) space if range is constant
Case 5: You Only Need Presence (Not Values)
The problem
Hash maps store key-value pairs. If you only need presence, you're wasting space.
Example: "Check if array contains duplicate"
Why hash maps are overkill
# Hash map when set is enough
seen = {}
for num in nums:
if num in seen:
return True
seen[num] = True # Don't need this value!What to use instead
Use set
# Cleaner and more efficient
seen = set()
for num in nums:
if num in seen:
return True
seen.add(num)
# Or even simpler
return len(nums) != len(set(nums))When to use:
- Only checking existence/presence
- Deduplication
- Membership testing
- Don't need associated data
Benefits:
- Clearer intent
- Slightly less memory
- Simpler API
For detailed comparison, see Hash Map vs Hash Set.
Decision Checklist
Before using a hash map, ask:
Do I need ordering?
- Yes → Use TreeMap/TreeSet or sort first
- No → Continue
Do I need range queries?
- Yes → Use prefix sum, segment tree, or sorted + binary search
- No → Continue
Is space critical (O(1) required)?
- Yes → Use two pointers, in-place, or Floyd's
- No → Continue
Is the key range small and known?
- Yes → Use array (direct indexing)
- No → Continue
Do I need associated values?
- No → Use set instead
- Yes → Hash map is appropriate
Common Mistakes
Mistake 1: Using hash map for sorted problems
# Two Sum II (sorted array) with hash map
# Suboptimal - should use two pointers for O(1) spaceMistake 2: Using hash map for small alphabet
# Counting a-z with hash map
# Overkill - should use array[26]Mistake 3: Using hash map when set suffices
# Contains duplicate with hash map
# Wasteful - should use setSummary
Hash maps are powerful, but not universal.
Don't use hash maps when:
- ❌ Need ordered data → TreeMap/sort
- ❌ Need range queries → Prefix sum/segment tree
- ❌ Space is critical → Two pointers/in-place
- ❌ Small fixed range → Array
- ❌ Only need presence → Set
The rule: Choose the simplest structure that meets your requirements.
Next steps:
- Learn hash map vs other structures
- Study hash map vs two pointers
- Master the complete hash map guide
Know when to use hash maps, and when to walk away.
Want to Practice LeetCode Smarter?
LeetCopilot is a free browser extension that enhances your LeetCode practice with AI-powered hints, personalized study notes, and realistic mock interviews — all designed to accelerate your coding interview preparation.
Also compatible with Edge, Brave, and Opera
