LeetCopilot Logo
LeetCopilot
LeetCode Pattern/Hash Map/5 Common Hash Map Mistakes That Fail Interviews (And How to Fix Them)

5 Common Hash Map Mistakes That Fail Interviews (And How to Fix Them)

LeetCopilot Team
Dec 19, 2025
7 min read
Hash MapCommon MistakesDebuggingInterview Prep
Your hash map solution keeps getting 'Wrong Answer.' Learn the 5 most common mistakes that trip up even experienced developers and how to fix them instantly.

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):

python
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):

python
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 value

The 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):

python
freq = {}
for char in s:
    freq[char] += 1  # KeyError if char not in freq!

Correct (safe):

python
# 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 Counter for 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):

python
# Lists are not hashable
key = [1, 2, 3]
groups[key] = []  # TypeError: unhashable type: 'list'

Correct (use immutable):

python
# Use tuple (immutable)
key = (1, 2, 3)
groups[key] = []  # Works!

# Or convert to string
key = str([1, 2, 3])
groups[key] = []  # Works, but less efficient

Common cases

For sorted characters (anagrams):

python
# Wrong
key = sorted(word)  # Returns list!

# Correct
key = ''.join(sorted(word))  # String
# Or
key = tuple(sorted(word))  # Tuple

For character counts:

python
# 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):

python
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):

python
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:

  1. Check for complement/condition
  2. 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):

python
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):

python
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 map before accessing?
  • Are you using .get(key, default)?
  • Are you using defaultdict or Counter when 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

python
# Before
seen[i] = num

# After
seen[num] = i

Fix 2: Missing key check

python
# Before
freq[char] += 1

# After
freq[char] = freq.get(char, 0) + 1

Fix 3: Mutable key

python
# Before
key = sorted(word)

# After
key = ''.join(sorted(word))

Fix 4: Wrong order

python
# 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] = i

Fix 5: Missing initialization

python
# Before
sum_count = {}

# After
sum_count = {0: 1}

Summary

The 5 most common hash map mistakes:

  1. Wrong key/value pair → Key = what you look up, value = what you need
  2. Not checking existence → Use .get(), if in, or defaultdict
  3. Mutable keys → Use tuples/strings, not lists
  4. Wrong duplicate handling → Check before adding
  5. Missing {0: 1} → Initialize for prefix sum problems

The debugging process:

  1. Identify which mistake you're making
  2. Apply the quick fix
  3. Test with edge cases

Next steps:

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

Related Tutorials