AlgoViz

Hash usage

easy 16 min

Hash maps and hash sets find a key by computing where it lives instead of searching for it, so insert, lookup and delete cost O(1) on average.

See it run

Use Python's dict and set to count, look up, group and remember in O(1) average time per operation.

Operations

put and get

Insert, update and read entries of a dict. The key is hashed straight to its slot, so no scan is needed.

Step 1 of 7

An empty dict

keyvalue
··

A dict maps keys to values. Python hashes each key to find its slot directly, so every step below costs O(1) on average, however big the dict gets.

Step 1: An empty dict

stock = {}                       # an empty dictstock["apple"] = 5               # insertstock["banana"] = 3stock["cherry"] = 8stock["apple"] = 6               # same key: value replacedprint(stock["banana"])           # 3print(stock.get("kiwi"))         # None, no errorprint(stock.get("kiwi", 0))      # 0, your defaultprint(len(stock))                # 3
Time
O(1) avg
Space
O(1) per entry
worst case
O(n) if keys collide
list of pairs
O(n) per lookup

Use d[k] when a missing key is a bug you want to hear about, and d.get(k, default) when missing is normal.

In the real world

The same hash usage doing real jobs. Pick one and step through it.

Browsers, CDNs and app servers keep pages in a map keyed by URL: a repeat request is a dict hit instead of a slow download.

Step 1 of 5

Six requests

requests

  1. /a0
  2. /b1
  3. /a2
  4. /c3
  5. /a4
  6. /b5

cache keys

  1. {}0
hits = 0misses = 0

Requests arrive for /a, /b, /a, /c, /a, /b. Each download is slow; a dict lookup is O(1) average.

Step 1: Six requests

def slow_download(url):    return "page " + url             # imagine 300 ms herecache = {}hits = misses = 0def fetch(url):    global hits, misses    if url in cache:        hits += 1        return cache[url]            # fast path    misses += 1    page = slow_download(url)        # the expensive call    cache[url] = page    return pagefor url in ["/a", "/b", "/a", "/c", "/a", "/b"]:    fetch(url)print(hits, misses)                  # 3 3

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Using a mutable object as a key

    critical

    Dict keys and set members must be hashable. Lists, dicts and sets are mutable, so Python refuses them; their hash could change after insertion and the entry would be lost. Convert to a tuple or frozenset.

    Wrong
    seen = {}seen[[1, 2]] = "value"     # TypeError: unhashable type: 'list'
    Right
    seen = {}seen[(1, 2)] = "value"     # tuples are immutable and hashableseen[tuple([1, 2])] = "v"  # convert when you start from a list
  • Incrementing a key that does not exist yet

    critical

    count[num] += 1 reads count[num] first, and a missing key raises KeyError on the very first occurrence.

    Wrong
    count = {}for num in [3, 1, 3]:    count[num] += 1        # KeyError: 3
    Right
    from collections import Counter, defaultdictcount = {}for num in [3, 1, 3]:    count[num] = count.get(num, 0) + 1# or: Counter([3, 1, 3]), or defaultdict(int)
  • Storing before checking in Two Sum

    major

    If you insert the current number before looking up its complement, a number can pair with itself: target 6 and the value 3 would match its own index.

    Wrong
    def two_sum(nums, target):    seen = {}    for i, num in enumerate(nums):        seen[num] = i                     # stored first        if target - num in seen:            return [seen[target - num], i]two_sum([3, 2, 4], 6)                     # [0, 0]: wrong
    Right
    def two_sum(nums, target):    seen = {}    for i, num in enumerate(nums):        if target - num in seen:          # check first            return [seen[target - num], i]        seen[num] = itwo_sum([3, 2, 4], 6)                     # [1, 2]
  • Changing a dict while looping over it

    major

    Adding or deleting keys during iteration raises RuntimeError: dictionary changed size during iteration. Loop over a copy of the keys, or build a new dict.

    Wrong
    stock = {"apple": 0, "kiwi": 4, "fig": 0}for k in stock:    if stock[k] == 0:        del stock[k]       # RuntimeError
    Right
    stock = {"apple": 0, "kiwi": 4, "fig": 0}for k in list(stock):      # a copy of the keys    if stock[k] == 0:        del stock[k]# or: stock = {k: v for k, v in stock.items() if v != 0}
  • Using in to search values

    minor

    x in d tests keys only. Checking values with x in d.values() is a linear scan, so doing it inside a loop turns O(n) into O(n²). Keep a reverse map or a set of values.

    Wrong
    owner = {"car": "ann", "bike": "bo"}names = ["ann", "cy", "bo"]print("ann" in owner)               # False: checks keysfor name in names:    if name in owner.values():      # O(n) every time        print(name)
    Right
    owner = {"car": "ann", "bike": "bo"}names = ["ann", "cy", "bo"]owners = set(owner.values())        # build once, O(n)for name in names:    if name in owners:              # O(1) average        print(name)
  • Reading a defaultdict creates the key

    minor

    Looking up a missing key in a defaultdict inserts it with the default value. A plain check like if groups[k] silently grows the dict and adds empty groups to your answer.

    Wrong
    from collections import defaultdictgroups = defaultdict(list)if groups["zzz"]:          # inserts "zzz": []    passprint(len(groups))         # 1
    Right
    from collections import defaultdictgroups = defaultdict(list)if "zzz" in groups:        # membership never inserts    passprint(len(groups))         # 0

Interview tips

  • How to explain it

    • Always state both costs: O(1) average for insert, lookup and delete, O(n) worst case when many keys collide.
    • Name the trade: a hash map is fast but unordered; a BST or TreeMap is O(log n) but sorted with range queries; an array is cheaper when keys are small integers.
    • Say what you store and why: "a dict from value to index so each complement check is O(1)".
    • Be ready to sketch a simple hash table (buckets, hash function, collision handling): see the hash implementation topic.
  • When to reach for each

    • Seen before, duplicate, visited, unique: a set.
    • Count, frequency, majority, top k: Counter or a dict of counts.
    • Pair with a target, index of a value: a dict from value to index.
    • Group by a property: defaultdict(list) with a canonical, hashable key.
    • Subarray with sum k: prefix sums in a dict seeded with {0: 1}.
    • Repeated expensive calls: a cache dict or functools.lru_cache.
  • Memory tricks

    • HASH: Hash function, Array of buckets, Store key-value pairs, Handle collisions.
    • The magic library: a spell turns the book title into a shelf number, so you walk straight to the shelf instead of checking them all.
    • Rhyme: hash the key to find the spot, mod by size, that's what you've got; collision? chain them in a row; O(1) average, watch it go.
    • Compute the location, do not search for it.
  • Consider something else when

    • You need sorted order, min or max, floor or ceiling: a balanced BST, a sorted list with bisect, or a heap for min and max only.
    • You need range queries: a sorted array with binary search, a BST or a segment tree.
    • Keys are small integers in a known range: a plain list indexed by the key is faster and smaller.
    • Memory is tight and the input is sorted: two pointers need O(1) extra space.