Your hash map solution looks right. You submit it. Wrong Answer.
You trace through the logic. It seems correct. But test case 47 fails, and you can't figure out why.
This is frustrating because hash map problems should be straightforward. But there are 5 common mistakes that trip up even experienced developers.
This guide shows you exactly what they are and how to fix them.
Mistake 1: Choosing the Wrong Key/Value Pair
The problem
You store the wrong thing as the key or value, making lookups impossible.
Example: Two Sum
❌ Wrong (index as key):
def twoSum(nums, target):
seen = {}
for i, num in enumerate(nums):
seen[i] = num # WRONG: Can't look up by value!
if target - num in seen:
return [seen[target - num], i]Why it fails: You need to look up by value (num), but you stored index as the key.
✅ Correct (value as key):
def twoSum(nums, target):
seen = {}
for i, num in enumerate(nums):
if target - num in seen:
return [seen[target - num], i]
seen[num] = i # Correct: value is key, index is valueThe rule
Key = what you look up
Value = what you need when you find it
For Two Sum:
- Look up by: complement (a number) → key is number
- Need when found: index → value is index
Mistake 2: Not Checking if Key Exists Before Access
The problem
Accessing a key that doesn't exist causes KeyError/undefined.
Example
❌ Wrong (crashes):
freq = {}
for char in s:
freq[char] += 1 # KeyError if char not in freq!✅ Correct (safe):
# Option 1: Use .get() with default
freq = {}
for char in s:
freq[char] = freq.get(char, 0) + 1
# Option 2: Check first
freq = {}
for char in s:
if char not in freq:
freq[char] = 0
freq[char] += 1
# Option 3: Use defaultdict
from collections import defaultdict
freq = defaultdict(int)
for char in s:
freq[char] += 1 # Safe - defaults to 0
# Option 4: Use Counter
from collections import Counter
freq = Counter(s)The rule
Always handle missing keys:
- Use
.get(key, default) - Check
if key in map - Use
defaultdict - Use
Counterfor frequency
Mistake 3: Using Mutable Objects as Keys
The problem
Lists, sets, and dicts are mutable and can't be used as hash map keys.
Example
❌ Wrong (TypeError):
# Lists are not hashable
key = [1, 2, 3]
groups[key] = [] # TypeError: unhashable type: 'list'✅ Correct (use immutable):
# Use tuple (immutable)
key = (1, 2, 3)
groups[key] = [] # Works!
# Or convert to string
key = str([1, 2, 3])
groups[key] = [] # Works, but less efficientCommon cases
For sorted characters (anagrams):
# Wrong
key = sorted(word) # Returns list!
# Correct
key = ''.join(sorted(word)) # String
# Or
key = tuple(sorted(word)) # TupleFor character counts:
# Wrong
from collections import Counter
key = Counter(word) # Counter is mutable!
# Correct
key = tuple(sorted(Counter(word).items()))The rule
Keys must be immutable:
- ✅ Numbers, strings, tuples, frozensets
- ❌ Lists, sets, dicts, Counters
Mistake 4: Not Handling Duplicates Correctly
The problem
Adding to map before checking causes issues with duplicates.
Example: Two Sum with duplicates
❌ Wrong (fails when target = 2 * num):
def twoSum(nums, target):
seen = {}
for i, num in enumerate(nums):
seen[num] = i # Add BEFORE checking
if target - num in seen:
return [seen[target - num], i]
# Test: nums = [3, 3], target = 6
# i=0: seen={3:0}, check 6-3=3, found! return [0, 0] ❌ (same index!)✅ Correct (check before adding):
def twoSum(nums, target):
seen = {}
for i, num in enumerate(nums):
if target - num in seen: # Check FIRST
return [seen[target - num], i]
seen[num] = i # Add AFTER
# Test: nums = [3, 3], target = 6
# i=0: check 6-3=3 (not found), add {3:0}
# i=1: check 6-3=3 (found!), return [0, 1] ✓The rule
Order matters:
- Check for complement/condition
- Then add current element
This naturally handles duplicates and prevents using the same element twice.
Mistake 5: Forgetting to Initialize {0: 1} for Prefix Sum
The problem
Prefix sum + hash map requires {0: 1} initialization to handle subarrays from index 0.
Example: Subarray Sum Equals K
❌ Wrong (misses subarrays from start):
def subarraySum(nums, k):
count = 0
prefix_sum = 0
sum_count = {} # Missing {0: 1}!
for num in nums:
prefix_sum += num
if prefix_sum - k in sum_count:
count += sum_count[prefix_sum - k]
sum_count[prefix_sum] = sum_count.get(prefix_sum, 0) + 1
return count
# Test: nums = [1, 2, 3], k = 3
# Misses subarray [1, 2] and [3]✅ Correct (with initialization):
def subarraySum(nums, k):
count = 0
prefix_sum = 0
sum_count = {0: 1} # Critical!
for num in nums:
prefix_sum += num
if prefix_sum - k in sum_count:
count += sum_count[prefix_sum - k]
sum_count[prefix_sum] = sum_count.get(prefix_sum, 0) + 1
return count
# Test: nums = [1, 2, 3], k = 3
# Correctly finds [1, 2] and [3]Why {0: 1} is needed
Conceptual: "There's one way to get sum 0: take nothing (empty prefix)."
Practical: When prefix_sum = k, we need prefix_sum - k = 0 to exist in the map.
The rule
For prefix sum + hash map problems:
- Always initialize with
{0: 1} - This handles subarrays starting from index 0
For detailed explanation, see Subarray Sum Mistakes.
Debugging Checklist
When your hash map solution fails, check:
1. Key/Value Design
-
Is the key what you're looking up?
-
Is the value what you need when you find it?
-
Are you storing the right data?
2. Existence Checks
-
Are you checking
if key in mapbefore accessing? -
Are you using
.get(key, default)? -
Are you using
defaultdictorCounterwhen appropriate?
3. Key Mutability
-
Are your keys immutable (strings, tuples, numbers)?
-
Did you convert lists to tuples or strings?
-
Are you using hashable types?
4. Duplicate Handling
-
Are you checking before adding (for Two Sum pattern)?
-
Are you handling the same element appearing twice?
-
Is your update order correct?
5. Initialization
-
For prefix sum: Did you initialize with
{0: 1}? -
For frequency: Did you handle first occurrence?
-
For grouping: Did you create empty list/set for new keys?
Quick Fixes
Fix 1: Wrong key/value
# Before
seen[i] = num
# After
seen[num] = iFix 2: Missing key check
# Before
freq[char] += 1
# After
freq[char] = freq.get(char, 0) + 1Fix 3: Mutable key
# Before
key = sorted(word)
# After
key = ''.join(sorted(word))Fix 4: Wrong order
# Before
seen[num] = i
if target - num in seen:
return [seen[target - num], i]
# After
if target - num in seen:
return [seen[target - num], i]
seen[num] = iFix 5: Missing initialization
# Before
sum_count = {}
# After
sum_count = {0: 1}Summary
The 5 most common hash map mistakes:
- Wrong key/value pair → Key = what you look up, value = what you need
- Not checking existence → Use
.get(),if in, ordefaultdict - Mutable keys → Use tuples/strings, not lists
- Wrong duplicate handling → Check before adding
- Missing {0: 1} → Initialize for prefix sum problems
The debugging process:
- Identify which mistake you're making
- Apply the quick fix
- Test with edge cases
Next steps:
- Study hash map key selection
- Learn handling duplicates
- Master subarray sum mistakes
Fix these 5 mistakes, and your hash map solutions will pass.
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
