Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Python
Stage 5: Specialization

Part 17 / Topic 3 of 20

Hashing

A hash table turns a key into a number (a hash) and uses that number to jump straight to the right storage slot, instead of checking every item one by one. Python's dict and set are hash tables. Average case: O(1) to look up, insert or delete a key. Worst case is O(n) (many different keys landing in the same slot), but this is rare in practice and not something you need to engineer around in everyday code. Think of a library that shelves books by the first letter of the author's surname: you jump straight to the "K" shelf instead of checking every book in the building.

Operation list dict / set
x in container O(n) O(1) average
insert / delete by key O(n) (search first) O(1) average
build from n items O(n) O(n)
def two_sum(prices: dict[str, int], budget: int) -> tuple[str, str] | None:
    """One pass: for each item, check if (budget - its price) was already seen."""
    seen: dict[int, str] = {}                  # price -> item name
    for name, price in prices.items():
        partner_price = budget - price
        if partner_price in seen:               # O(1) average
            return seen[partner_price], name
        seen[price] = name
    return None

cart = {"notebook": 60, "pen": 10, "bottle": 250, "umbrella": 340, "lunchbox": 190}
print(two_sum(cart, 400))      # ('notebook', 'umbrella')
print(two_sum(cart, 999))      # None

A nested-loop version of the same check is O(n²): for every item, scan every other item for a partner. The dict version is O(n): one pass, and "have I seen a matching partner?" is a single hash lookup.

collections.Counter and collections.defaultdict are dicts with a job already built in:

from collections import Counter

deliveries = ["411001", "110001", "411001", "560001", "411001", "110001"]
counts = Counter(deliveries)
print(counts.most_common(1)[0])     # ('411001', 3)

Real-world example: the two_sum function above is exactly how a billing app would find two cart items that together use up a ₹400 gift voucher exactly, checking each item once instead of comparing every pair.

⚠️ Only values that never change while they are a dict key or set member may be hashed (so list and dict cannot be dict keys; tuple and frozenset can, if their contents are hashable). Part 14 covers the __hash__/__eq__ rules for your own classes.

Practice: two-sum style pair finding (find two numbers that add up to a target); first-duplicate or first-unique-item detection in a stream; grouping items by a computed signature (anagrams, same digits, same remainder).

Practice on LeetCode - start here: Two Sum · Ransom Note · Majority Element · Group Anagrams · Longest Consecutive Sequence

Show the full practice list (14 more problems)

Core practice - gentler first:

Stretch - tougher; come back once the core feels comfortable:

Problem Difficulty
Encode and Decode TinyURL Medium
Insert Delete GetRandom O(1) Medium
4Sum II Medium
Brick Wall Medium

Full program: examples/03_hashing.py.

Exercise 3: Hashing — first repeated customer

Scenario: A support queue log lists customer names in the order they called. You want the FIRST name that calls a second time. What to do: Write first_repeat(calls: list[str]) -> str | None using a set to remember names seen so far, in one O(n) pass (no nested loop). Print the result for the data below, then print it again for a list with no repeats.

Starting data:

CALLS = ["Ravi", "Asha", "Imran", "Ravi", "Kavya"]
NO_REPEATS = ["Ravi", "Asha", "Imran"]

Sample output:

First repeat: Ravi
First repeat (no repeats): None
Show the solution to Exercise 3
"""Exercise 3: Hashing - first repeated customer.

Run:   python ex02.py   (macOS/Linux: python3 ex02.py)
"""

CALLS = ["Ravi", "Asha", "Imran", "Ravi", "Kavya"]
NO_REPEATS = ["Ravi", "Asha", "Imran"]


def first_repeat(calls: list[str]) -> str | None:
    seen: set[str] = set()
    for name in calls:
        if name in seen:
            return name
        seen.add(name)
    return None


def main() -> None:
    print("First repeat:", first_repeat(CALLS))
    print("First repeat (no repeats):", first_repeat(NO_REPEATS))


if __name__ == "__main__":
    main()

💡 Hint: Loop once; if the name is already in seen, return it immediately; otherwise add it to seen.

Search the guide