Skip to main content
HashMap Pattern

What is HashMap?

HashMap (or HashTable/Dictionary) provides O(1) average-case lookup, insertion, and deletion by mapping keys to values using a hash function.
Quick Recognition: If you need O(1) lookup, frequency counting, or want to trade space for time, HashMap is your friend!

Pattern Recognition Checklist

Use HashMap When

  • Need O(1) lookup by key
  • Counting frequencies of elements
  • Finding pairs/complements (like Two Sum)
  • Grouping elements by property
  • Caching/Memoization

Don't Use When

  • Need sorted order (use TreeMap)
  • Range queries required
  • Space is very constrained
  • Keys are unhashable (like lists)

When to Use

Frequency Counting

Count occurrences of elements

Two Sum Variants

Find pairs/groups with specific properties

Caching/Memoization

Store computed results

Grouping/Indexing

Group elements by property

Pattern Variations

1. Two Sum (Classic HashMap)

def two_sum(nums, target):
    """Find indices of two numbers that sum to target"""
    seen = {}  # value -> index
    
    for i, num in enumerate(nums):
        complement = target - num
        if complement in seen:
            return [seen[complement], i]
        seen[num] = i
    
    return []

2. Frequency Counter

from collections import Counter

def top_k_frequent(nums, k):
    """Return k most frequent elements"""
    count = Counter(nums)
    return [num for num, _ in count.most_common(k)]

def is_anagram(s, t):
    """Check if t is anagram of s"""
    return Counter(s) == Counter(t)

3. Group By (Anagrams)

from collections import defaultdict

def group_anagrams(strs):
    """Group strings that are anagrams of each other"""
    groups = defaultdict(list)
    
    for s in strs:
        key = tuple(sorted(s))  # or count-based key
        groups[key].append(s)
    
    return list(groups.values())

4. Prefix Sum with HashMap

def subarray_sum_equals_k(nums, k):
    """Count subarrays with sum exactly k"""
    count = 0
    prefix_sum = 0
    sum_count = {0: 1}  # prefix_sum -> frequency
    
    for num in nums:
        prefix_sum += num
        
        # If (prefix_sum - k) exists, those many subarrays sum to k
        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

5. Longest Consecutive Sequence

def longest_consecutive(nums):
    """Find length of longest consecutive sequence"""
    num_set = set(nums)
    max_length = 0
    
    for num in num_set:
        # Only start counting from sequence start
        if num - 1 not in num_set:
            current = num
            length = 1
            
            while current + 1 in num_set:
                current += 1
                length += 1
            
            max_length = max(max_length, length)
    
    return max_length

6. LRU Cache (HashMap + Doubly Linked List)

from collections import OrderedDict

class LRUCache:
    def __init__(self, capacity):
        self.cache = OrderedDict()
        self.capacity = capacity
    
    def get(self, key):
        if key not in self.cache:
            return -1
        self.cache.move_to_end(key)
        return self.cache[key]
    
    def put(self, key, value):
        if key in self.cache:
            self.cache.move_to_end(key)
        self.cache[key] = value
        if len(self.cache) > self.capacity:
            self.cache.popitem(last=False)

Classic Problems

Pattern: Store complement, check on each iterationKey: HashMap trades space for time O(n^2) to O(n)
Pattern: Compare character frequency countsVariants: Counting sort (26 letters), Counter equality
Pattern: HashSet for seen elementsVariants: Within k indices, within t value difference
Pattern: Count frequency, find first with count 1Key: Two passes - count, then find
Pattern: Prefix sum with HashMapKey: Store prefix_sum frequencies, look for (current - k)

Common Mistakes

Avoid These Pitfalls:
  1. Unhashable keys: Lists cannot be dict keys in Python, use tuples
  2. Missing key errors: Use .get() or check existence before access
  3. Hash collisions: Know when worst case is O(n) lookup
  4. Mutating keys: Don’t modify objects used as keys

Complexity Quick Reference

OperationAverageWorst CaseNote
InsertO(1)O(n)Worst case with bad hash
LookupO(1)O(n)Worst case with collisions
DeleteO(1)O(n)Worst case with chaining
IterateO(n)O(n)All keys/values

Interview Problems by Company

ProblemCompanyKey Concept
Two SumAll FAANGComplement lookup
Valid AnagramAmazon, MetaCharacter frequency
Contains DuplicateAllHashSet for seen
First Unique CharAmazonFrequency count
Ransom NoteMicrosoftCharacter counting

Interview Tips

Script for interviews:
  1. “I’ll use a HashMap to get O(1) lookup time.”
  2. “I’ll store [key] mapping to [value].”
  3. “This trades O(n) space for O(1) lookup time.”
  4. “For each element, I check if [complement/target] exists.”
  5. “Total time is O(n) with O(n) space.”
Interviewer SaysYou Should Think
”Can you do it in O(n)?”HashMap to avoid nested loop
”Count occurrences”Frequency counter
”Find pair that sums to…”Store complements
”Group by property”Key = property, value = list
”Check if seen before”HashSet
HashMap: When you need key-value pairs
  • Two Sum (value → index)
  • Frequency counting (element → count)
HashSet: When you only need presence check
  • Contains Duplicate (seen set)
  • Unique elements (deduplication)

Practice Problems

ProblemDifficultyLink
Two SumEasyLeetCode 1
Valid AnagramEasyLeetCode 242
Group AnagramsMediumLeetCode 49
Subarray Sum Equals KMediumLeetCode 560
LRU CacheMediumLeetCode 146

Practice Roadmap

1

Day 1: Basic Lookup

  • Solve: Two Sum, Contains Duplicate
  • Focus: Complement pattern, seen set
2

Day 2: Frequency Counting

  • Solve: Valid Anagram, First Unique Character
  • Focus: Counter/frequency map usage
3

Day 3: Grouping

  • Solve: Group Anagrams, Word Pattern
  • Focus: Key design for grouping
4

Day 4: Advanced

  • Solve: LRU Cache, Subarray Sum = K
  • Focus: HashMap + other data structures
Interview Tip: When you need O(1) lookup or counting frequencies, HashMap is almost always the answer.