Data Structures & Algorithms chapters (13)
  1. 01Introduction to DSA
  2. 02Arrays & Strings Algorithms
  3. 03Searching & Sorting Algorithms
  4. 04Asymptotic Analysis & Complexity
  5. 05Linked Lists
  6. 06Stacks & Queues
  7. 07Hashing & Hash Tables
  8. 08Recursion & Backtracking
  9. 09Binary Trees & BST
  10. 10Heaps & Priority Queues
  11. 11Graphs & Graph Algorithms
  12. 12Greedy Algorithms & Bit Manipulation
  13. 13Dynamic Programming (DP)

Chapter 07

Hashing & Hash Tables

2 topics · 1 sections · beginner-friendly study notes · Updated

Share with friends:WhatsAppTelegram

Embed on your site

Free for teachers, schools and blogs. Please keep the attribution link.

Preview

A hash table maps keys to array indices using a hash function, giving average O(1) insert, search and delete.

Collisions are resolved by chaining or open addressing; hash maps/sets turn many O(n^2) scans into O(n).

Hash maps are the most used data structure in interviews; GATE asks probing outcomes and expected probe counts.

Caches, symbol tables, database indexes, deduplication, counting, password storage (with cryptographic hashes).

1

Hash Functions & Collisions

A hash function h(k) maps a key to an index in [0, m-1]; two different keys with the same index collide. Collisions are inevitable (pigeonhole principle) when the key universe is larger than m and are handled by separate chaining or open addressing.

In short: Turn a key into a bucket number; if two keys land in one bucket, resolve it with a strategy.

Hash table: key → hash() → bucket index, with collision chain
Hash table: key → hash() → bucket index, with collision chain

Think about it

GATE questions: insert a sequence into a table with probing, count collisions, expected probes, load factor.

Good hash: deterministic, uniform, fast.

Division method h(k) = k mod m (choose m prime, not a power of 2 which only uses low bits).

Multiplication method: floor(m * frac(k*A)) with A about 0.618.

String hash: polynomial s[0]*p^(n-1)+...

+s[n-1] mod m (rolling hash for Rabin-Karp).

Load factor alpha = n/m.

Chaining: each slot holds a list; expected search time Theta(1 + alpha) under simple uniform hashing; alpha may exceed 1; worst case O(n) if all keys hash together (Java HashMap converts long buckets to trees: O(log n)).

Open addressing: all keys in the table (alpha <= 1): linear probing h(k,i)=(h(k)+i) mod m suffers primary clustering; quadratic probing (h + c1*i + c2*i^2) suffers secondary clustering and may not visit all slots unless m is prime and alpha < 0.5 (or m is a power of two with triangular numbers); double hashing h1 + i*h2 with h2 coprime to m minimizes clustering.

Expected probes for unsuccessful search with open addressing about 1/(1-alpha); successful about (1/alpha) ln(1/(1-alpha)).

Deletion in open addressing needs tombstones (mark deleted) else probing chains break.

Resize when alpha exceeds threshold (e.

g.

0.75): allocate 2m, rehash all keys O(n), amortized O(1) insert.

Python dict/set: average O(1); keys must be hashable (immutable).

Equal objects must have equal hashes; a mutable key changing hash breaks lookup.

Cryptographic hashes (SHA-256) differ from table hashes: collision-resistance, not speed.

Key points

  • Load factor: alpha = n/m (entries / buckets).
  • Primary clustering: Long runs of filled slots forming under linear probing.
  • Tombstone: Marker for deleted slot in open addressing.
  • Separate chaining: Each bucket stores a linked list of keys.
  • Linear probing, m=7, h(k)=k mod 7: insert 15 (1), 22 (1 -> 2), 29 (1 -> 2 -> 3): slots 1,2,3.
  • Open addressing needs n <= m; chaining has no such limit.

Example

Code
Chaining table and linear probing:
class ChainedHash:
    def __init__(self, m=8):
        self.m, self.n = m, 0
        self.t = [[] for _ in range(m)]
    def put(self, k, v):
        b = self.t[hash(k) % self.m]
        for i, (kk, _) in enumerate(b):
            if kk == k: b[i] = (k, v); return
        b.append((k, v)); self.n += 1
        if self.n / self.m > 0.75: self._resize()
    def get(self, k):
        for kk, v in self.t[hash(k) % self.m]:
            if kk == k: return v
        raise KeyError(k)
    def _resize(self):
        old = [kv for b in self.t for kv in b]
        self.m *= 2; self.t = [[] for _ in range(self.m)]; self.n = 0
        for k, v in old: self.put(k, v)

def linear_probe_insert(table, key):
    m = len(table); i = key % m
    for step in range(m):
        j = (i + step) % m
        if table[j] is None:
            table[j] = key; return j
    raise OverflowError
2

HashMap Patterns & Two-Sum

A hash map trades O(n) memory for O(1) average lookups, which converts nested loops into a single pass: store what you have seen (value, index, count, prefix sum) and query for the complement or duplicate in constant time.

In short: Remember what you have already seen so you can answer "have I seen the match?" instantly.

Think about it

Single most useful interview tool; many problems are one hash-map insight away from linear time.

Two-sum: for each x look up target - x in a dict of value->index, then insert x (after the lookup to avoid using the same element twice): O(n) time, O(n) space vs O(n^2) brute force; with sorted input two pointers use O(1) space.

Duplicates (contains duplicate): set of seen.

Frequency count: Counter; majority element, top-K frequent, first non-repeating char.

Group anagrams: key = sorted(word) or a 26-count tuple.

Subarray sum equals K: prefix-sum frequency map.

Longest consecutive sequence: put all in a set, start counting only from numbers x where x-1 is absent: O(n).

Longest substring without repeats: char -> last index.

Isomorphic strings / word pattern: two-way mapping.

Intersection of arrays: set lookups.

LRU: hash map + doubly list.

Pitfalls: mutable keys (lists) unhashable in Python (use tuple); worst-case O(n) per operation under adversarial collisions (anti-hash tests) - sort-based or tree-based maps give O(log n) guaranteed; iteration order is insertion order in Python 3.7+ dict but unspecified in a set and in a C++ unordered_map.

Hash set vs map: set stores keys only.

Key points

  • Complement lookup: Query target - x instead of scanning for it.
  • Frequency map: key -> count of occurrences.
  • Canonical key: Normalized form (sorted letters) used to group equivalents.

Example

Code
Hash map patterns:
def two_sum(nums, target):
    seen = {}
    for i, x in enumerate(nums):
        if target - x in seen:
            return [seen[target - x], i]
        seen[x] = i                       # insert AFTER lookup
    return []

from collections import defaultdict, Counter

def group_anagrams(words):
    g = defaultdict(list)
    for w in words:
        g[tuple(sorted(w))].append(w)
    return list(g.values())

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

def first_unique_char(s):
    c = Counter(s)
    for i, ch in enumerate(s):
        if c[ch] == 1: return i
    return -1

Solved examples

Example 01 · Basic

Table size 10, h(k)=k mod 10, linear probing. Insert 12, 22, 32, 42. Slots?

Given Data:
    Required To Find:

    Positions

    Formula Applied:—
    Step-by-Step Solution:
    Step 1: 12 -> 2.
    Step 2: 22 -> 2 taken, 3.
    Step 3: 32 -> 2,3 taken, 4.
    Step 4: 42 -> 5.
    Final Answer: Slots 2, 3, 4, 5 (primary clustering)

    Approach note: Look at the run: later keys travel farther.

    Example 02 · Intermediate

    Chaining, m = 7, insert keys 50, 700, 76, 85, 92, 73, 101 with h(k)=k mod 7. Longest chain?

    Given Data:
      Required To Find:

      Max chain length

      Formula Applied:—
      Step-by-Step Solution:
      Step 1: 50->1, 700->0, 76->6, 85->1, 92->1, 73->3, 101->3.
      Step 2: Bucket 1: 50, 85, 92 (3). Bucket 3: 73, 101 (2).
      Final Answer: 3 (bucket 1); load factor 7/7 = 1

      Approach note: Compute k mod m carefully; 700 mod 7 = 0.

      Example 03 · Advanced

      Two-sum on [3, 3] with target 6: why must lookup happen before insert?

      Given Data:
        Required To Find:

        Reasoning

        Formula Applied:—
        Step-by-Step Solution:
        Step 1: i=0: need 3, not seen; store 3->0.
        Step 2: i=1: need 3, found at 0 -> [0,1].
        Step 3: If insertion came first, a single [3] with target 6 would wrongly match itself.
        Final Answer: [0, 1]; lookup-then-insert prevents pairing an element with itself

        Approach note: Input [3] target 6 must return empty.

        Example 04 · Basic

        Hash table size m = 7, keys 10, 20, 15 inserted with h(k)=k mod 7 and chaining. List the chain at slot 1.

        Given Data:
          Required To Find:

          Keys in slot 1

          Formula Applied:—
          Step-by-Step Solution:
          Step 1: 10 mod 7 = 3
          Step 2: 20 mod 7 = 6
          Step 3: 15 mod 7 = 1
          Step 4: Only 15 hashes to slot 1
          Final Answer: Slot 1: 15 (alone)

          Approach note: Load factor α = n/m; chaining keeps α flexible.

          Real-world applications

          DSA

          Using Hashing & Hash Tables in real projects

          Caches, symbol tables, database indexes, deduplication, counting, password storage (with cryptographic hashes).

          Mechanism: Write small programs, read errors carefully, then grow complexity only after the basics are solid.

          Common mistakes

          ❌ Myth: Hash table operations are always O(1).

          Why this is wrong: Average O(1) assumes uniform hashing and bounded load factor; adversarial or poor hashes degrade to O(n).

          ✅ Verified Truth: Average O(1), worst case O(n) (or O(log n) with tree buckets).

          ⚠️ Exam Tip: Always say average vs worst.

          ❌ Myth: Using a power of two as table size is fine with k mod m.

          Why this is wrong: Only the low bits of k are used, causing clustering for patterned keys.

          ✅ Verified Truth: Prefer a prime m with the division method (or mix bits first).

          ⚠️ Exam Tip: GATE: choose prime, not close to a power of 2.

          ❌ Myth: Deleting from open addressing just clears the slot.

          Why this is wrong: It breaks probe chains for keys that probed past that slot.

          ✅ Verified Truth: Mark as tombstone (DELETED) and treat it as occupied during search.

          ⚠️ Exam Tip: Mention tombstones whenever asked about deletion.

          Revision notes

          A hash table maps keys to array indices using a hash function, giving average O(1) insert, search and delete. Collisions are resolved by chaining or open addressing; hash maps/sets turn many O(n^2) scans into O(n).

          High-Yield Quick Revision Points

          1. h(k)=k mod m (prime m); load factor alpha = n/m; resize at ~0.75, amortized O(1)
          2. Chaining: Theta(1+alpha); open addressing needs alpha<1, tombstones for delete
          3. Linear: primary clustering; quadratic: secondary; double hashing best
          4. Two-sum: lookup complement before inserting; prefix-sum map; group by canonical key
          5. Average O(1), worst O(n)

          Practice questions

          Question 1 · MCQ (GATE)

          Load factor of a table with 15 keys and 20 slots:

          Question 2 · MCQ (GATE)

          Which resolves collisions without extra memory outside the table?

          Question 3 · MCQ (GATE)

          Primary clustering is associated with:

          Question 4 · MCQ (Interview)

          Average time of two-sum using a dict:

          Question 5 · MCQ (GATE)

          Expected chain length under simple uniform hashing: