Data Structures & Algorithms · Module 3 · Lesson 21 min read

Hashing Patterns

Pattern 1: "Have I seen the complement?" (Two Sum)

Find two numbers that add to a target. For each number x, check whether target - x is already in a dict of seen values. O(n) time instead of O(n²).

Pattern 2: Frequency counting

Count things in a dict or Counter, then compare counts:

  • Are two words anagrams? Compare their letter counts.
  • What's the most common item?
  • Find the first unique character.

Pattern 3: Grouping by a key

Build a key for each item and group items that share it:

  • Group anagrams: the key is "".join(sorted(word)).
  • Group people by city, or numbers by remainder.

Pattern 4: Prefix sum + hash map

Count subarrays with sum k: store how many times each running total has appeared. If running - k was seen before, those subarrays sum to k.

Pattern 5: Set for existence

  • Remove duplicates: list(dict.fromkeys(items)) keeps the order.
  • Longest consecutive sequence: put everything in a set and only start counting from numbers whose x - 1 isn't present. O(n).

💡 The trade-off: hashing uses O(n) extra memory to save time. Mention it in interviews.

Example

Python
from collections import Counter, defaultdict

def two_sum(nums, target):
    seen = {}                          # value → index
    for i, x in enumerate(nums):
        if target - x in seen:
            return seen[target - x], i
        seen[x] = i
    return None

def is_anagram(a, b):
    return Counter(a) == Counter(b)

def group_anagrams(words):
    groups = defaultdict(list)
    for w in words:
        groups["".join(sorted(w))].append(w)
    return list(groups.values())

def longest_consecutive(nums):
    s, best = set(nums), 0
    for x in s:
        if x - 1 not in s:             # start of a run
            length = 1
            while x + length in s:
                length += 1
            best = max(best, length)
    return best

print(two_sum([2, 7, 11, 15], 9))                     # (0, 1)
print(is_anagram("listen", "silent"))                 # True
print(group_anagrams(["eat", "tea", "tan", "ate", "nat"]))
# [['eat', 'tea', 'ate'], ['tan', 'nat']]
print(longest_consecutive([100, 4, 200, 1, 3, 2]))    # 4  (1, 2, 3, 4)