Data StructureData StructureA way of organising data in memory so that certain operations, like lookup, insert or remove, are fast.e.g. Arrays, hash tables, stacks, trees
DSA Learning Studio · Core Data Structures

Arrays & Hashing — jump straight to the answer

Contiguous memory and O(1) indexing, dynamic arrays and amortized growth, hash functions, collisions, load factor, Python’s list, dict and set — and the hashing patterns behind a huge share of interview problems.

Difficulty: Beginner → Intermediate (advanced section: Upper-intermediate) Reading time: ~80 minutes (+ 30 min exercises) Language: Python 3.8+

AChapter introduction

Prerequisites

You should be comfortable with Python variables, loops, functions, lists and dictionaries at the “I have used them” level, and with Big-O notation (O(1), O(n), O(n²)). If Big-O is new, read Chapter 01 · Time & Space Complexity first. No mathematics beyond the remainder operator % and simple fractions is needed.

Learning objectives

After completing this chapter you will be able to:

  1. Explain why an array element can be read in O(1) time using the address formula, and why inserting in the middle costs O(n).
  2. Explain how a dynamic array (Python’s list) grows, and prove that appending is amortized O(1).
  3. Describe a hash table: hash function, buckets, collisions, separate chaining, open addressing and load factor.
  4. State when hash operations are O(1) on average and why their worst case is O(n).
  5. Implement a dynamic array and a hash map from scratch in Python, and know the built-in equivalents.
  6. Recognise and apply the core hashing patterns: seen-set, complement lookup, frequency count, canonical-key grouping and prefix-sum + hash map.
The one-sentence promise An array turns “give me item number i” into one address calculation; a hash table turns “give me the item called k” into the same kind of jump — so both answer their question in O(1) time instead of searching. [1][2]
How the visuals in this chapter are made This environment has no image-generation model, so every “whiteboard” illustration is drawn in code: a small sketch renderer produces hand-drawn-style strokes and handwriting labels as SVG from the actual data in each example. All four interactive labs are fully working. The figures use a deliberately simple toy hash (sum of character codes mod 8) so you can check every number by hand; real hash functions are far better, as Section F explains.

BFundamental understanding

What is an array?

An array is a fixed number of equally sized slots laid out next to each other in memory. Because the slots are contiguous and the same size, the machine can compute where slot i lives with one multiplication and one addition, instead of walking there. MIT’s 6.006 describes this as the array’s defining strength: reading or writing any position is constant time in the word-RAM model. [1]

Formal definition A static array of length n is a contiguous block of memory holding n elements of equal size s, starting at a base address b. Element i (for 0 ≤ i < n) is stored at address b + i·s, so it can be accessed in O(1) time. A dynamic array additionally supports adding and removing elements at the end by occasionally moving to a larger or smaller block. [1]
Simple English definition An array is a row of numbered lockers. If you know the locker number, you walk straight to it — you never have to open the lockers before it.

What is hashing?

Arrays are fast only when you already know the position. Very often we know a key instead — a username, a word, a product ID — and want its associated value. A hash table fixes this by using a hash function to turn the key into a number, then using that number (modulo the table size) as an array index. [2][3]

Formal definition A hash table stores a set of keys (optionally with values) in an array of m slots called buckets. A hash function h maps every possible key to a bucket index in {0, 1, …, m−1}. Two different keys with the same index form a collision, which must be resolved — typically by separate chaining (each bucket holds a small list) or open addressing (probe other slots of the same array). The load factor is α = n/m, where n is the number of stored keys. [2][3][12]
Simple English definition A hash table is a coat check. You hand over your coat and get ticket 37; the attendant goes straight to hook 37. The “hash function” is the rule that turns your name into a hook number, so you don’t even need to keep the ticket.

Why do these concepts exist?

Both structures exist to avoid searching. Without an array, finding the 500th item means walking past 499 others (as in a linked list). Without hashing, checking “have I seen this value?” means comparing against everything stored so far — O(n) per question and O(n²) for a whole list. Hashing converts those comparisons into a computed jump, which is why Python uses hash tables for dict and set and even for most namespaces. [5][18]

A little history

Hashing is older than most programming languages. In January 1953, Hans Peter Luhn wrote an internal IBM memorandum that used hashing with chaining. [12] Linear probing, the simplest form of open addressing, was first analysed by Donald Knuth in 1963. [13] Later milestones in the Advanced section — Bloom filters (1970), consistent hashing (1997) and cuckoo hashing (2001) — all build on the same idea. [15][16][14]

Fundamental principles

  1. Position is computed, not searched. Array index → address by arithmetic; key → index by hashing. [1][2]
  2. Contiguity has a price. Keeping elements packed means inserting or deleting in the middle must shift everything after it. [1]
  3. Growth is paid in rare, big installments. A dynamic array (and a hash table) occasionally copies everything into a bigger block; spread over many cheap operations, the cost per operation stays constant on average. [1][2]
  4. Equal keys must hash equally. The only hard rule for a hash function is that objects which compare equal produce the same hash; everything else is about speed. [7]

CThe problem statement

The dictionary (lookup) problem

ComponentSpecification
DataA changing collection of n items, each identified by a key (a number, string, tuple …).
Operationsinsert(k, v), find(k), delete(k) — the “dynamic set” or dictionary interface. [2]
Outputfind(k) returns the stored value or reports that k is absent.
GoalMake every operation as close to constant time as possible, even when n is in the millions.

Why the naive approach is inefficient

Store pairs in an unsorted list and scan for the key: each find costs O(n), and Python’s x in list is exactly such a linear scan. [6] Doing that once per element of an input — the classic “find duplicates” loop — costs O(n²); for n = 105 that is about 5·109 comparisons.

Limitations of alternative approaches

Keeping the list sorted allows binary search in O(log n), but every insertion must shift elements to keep the order, costing O(n). [1] A balanced binary search tree gives O(log n) for everything and keeps keys ordered, which is valuable — but if you never need order, you are paying log n for nothing. Direct addressing (an array indexed by the key itself) is O(1) but only works when keys are small integers; a table indexed by every possible 64-bit ID would be absurdly large. [2]

How hashing improves the solution

Hashing keeps the O(1) jump of direct addressing but compresses the huge key space into a table of size m = Θ(n). With a good (randomly chosen) hash function and the table kept proportional to n, MIT 6.006 shows that the expected chain length is 1 + (n−1)/m = O(1), so insert, find and delete take expected amortized O(1) time. [2]

Real-world analogy: the library (Illustrative analogy.) Finding a book by walking every shelf is linear search. Finding it by its shelf number is array indexing. A hash table is the catalogue rule “first letter of the author’s surname tells you the aisle”: you jump to the right aisle immediately and only glance at the few books there. If one aisle gets crowded (many authors named Smith), searching that aisle slows down — that is a collision, and the library’s answer is to add aisles before they get too full (the load factor).

DVisual whiteboard explanations

All diagrams in this chapter use one colour language:

Blue — original data, arrays, memory blocks Green — successful results, found items, new slots Red — deletions, collisions, wasted work Yellow/orange — active index, current pointer, probe Purple — links, chains, hash mapping Black — labels and definitions
Figure D.1 · Memory representationIndex → address by arithmetic
array slotslot being readaddress calculationindex & address labels
  1. Six 8-byte slots start at base address 1000 (illustrative numbers).
  2. To read A[4], compute 1000 + 4 × 8 = 1032 and fetch that address directly.
  3. The cost is the same for A[0] or A[1 000 000]: one multiply, one add, one memory read.
Technical interpretation: random access is O(1) because the address is a closed-form function of the index. [1] In CPython each slot of a list holds a reference to an object, which is why a list can mix types while still indexing in constant time. [4]
Figure D.2 · Before and afterInserting in the middle shifts the tail
unchangedshifted one slot rightnew elementdeleted element
  1. Insert 15 at index 1: elements 20, 30, 40, 50 each move one slot right (4 moves), then 15 is written.
  2. Delete index 0 (the 10): everything after it moves one slot left to close the gap.
  3. Appending at the end moves nothing.
Technical interpretation: insert/delete at index i cost Θ(n − i) moves — O(n) at the front, O(1) at the back. Python documents list.insert and list.pop(i) as O(n − i) for this reason. [6]
Figure D.3 · Internal workingKey → hash → bucket (separate chaining)
keyhash mapping & chain linksbucket arraycollisionstored entry
  1. Toy hash: add the character codes, then take mod 8. "cat" → 99+97+116 = 312 → 312 mod 8 = 0.
  2. "act" has the same letters, so the same sum: it also lands in bucket 0 — a collision. Bucket 0 now holds a chain of two entries.
  3. "dog" (314 → 2) and "fish" (426 → 2) collide in bucket 2; "bird" → 1 and "ant" → 3 have buckets to themselves.
Technical interpretation: a lookup hashes the key, jumps to one bucket, and compares only against that bucket’s chain. With n = 6 keys and m = 8 buckets, α = 0.75. (The toy hash is bad on purpose: every anagram collides. Real hashes mix positions — see Section F.) [2][3]
Figure D.4 · Step-by-step executionOpen addressing with linear probing
key placedprobe pathoccupied — try next slotempty slot
  1. Same six keys, same toy hash, but every key must live in the 8-slot array. Insert in order: cat, bird, act, dog, fish, ant.
  2. cat → 0 and bird → 1 land at home. act wants 0 (taken), tries 1 (taken), lands in 2. dog wants 2 (now taken) → 3. fish wants 2 → 3 → 4. ant wants 3 → 4 → 5.
  3. Slots 0–5 now form one solid run — a primary cluster. Any key hashing into it must walk to its end.
Technical interpretation: open addressing stores keys in the array itself and follows a probe sequence on collision; clusters grow as α approaches 1, which is why the load factor must stay well below 1. [3][13]
Figure D.5 · Time complexity visualizationWhy appending is amortized O(1)
existing elementcopied during resizenewly appendedempty capacity (dashed)
  1. Capacity starts at 1. Each time the block is full, allocate one twice as large and copy everything across.
  2. Appending 9 items triggers copies of 1, 2, 4 and 8 elements — 15 copies in total, fewer than 2 × 9.
  3. In general the copies form 1 + 2 + 4 + … < 2n, so n appends cost O(n) in total.
Technical interpretation: individual appends are occasionally Θ(n), but the average over any sequence is O(1) — amortized constant time. CPython’s list over-allocates on growth for the same reason. [1][4][6]

EInteractive lab

All labs below work. Change the inputs, step forwards and backwards, and watch the state panel explain each step.

Lab 1 · ArraysIndex, insert, delete and append — watch memory move
Lab 2 · Hash tableInsert, search and delete with chaining or linear probing
Lab 3 · Pattern: complement lookupTwo Sum, one pass with a hash map
index_of (value → index):
Lab 4 · Pattern: canonical keyGroup anagrams by sorted letters
groups (sorted key → words):

FInternal working

F.1 Static arrays in memory

A static array is one allocation of n · s bytes. Reading A[i] executes three steps: (1) multiply i by the element size s; (2) add the base address; (3) load the word at that address. None of the steps depends on n. [1] Because neighbouring elements share cache lines, scanning an array front to back is also very fast in practice.

F.2 Python’s list is a dynamic array of references

CPython implements lists as variable-length arrays, not linked lists: the list object holds a pointer to a contiguous array of references to the element objects, so indexing cost does not depend on the list’s size. [4] When the array runs out of room, CPython allocates extra space so that the next few appends need no reallocation. [4] Python’s documentation therefore lists append as amortized O(1), insert(i, x) and pop(i) as O(n − i), and x in list as O(n). [6]

F.3 Execution flow of a dynamic-array append

  1. If size < capacity: write the value at index size, increment size. Done — O(1).
  2. Otherwise allocate a new block of (say) twice the capacity.
  3. Copy all size existing elements into the new block — Θ(n).
  4. Release the old block, then perform step 1.

F.4 Hash functions

A hash function must be deterministic (the same key always gives the same value), fast to compute, and should spread keys uniformly over the buckets. [3] Python’s rule is stricter about one thing only: objects that compare equal must have the same hash value. [7] That is also why mutable containers such as lists and dicts are not hashable — if a key’s contents changed, its hash would change and the table could no longer find it. [8][5]

The toy hash in the figures (sum of character codes) violates “spread uniformly”: every anagram collides. The usual fix for strings is a polynomial rolling hash, h(s) = s₀·pk−1 + s₁·pk−2 + … + sk−1 (mod M), which weights each position differently so that “cat” and “act” differ. [22] Lab 2 lets you switch between the two and see the collisions disappear.

F.5 From hash to bucket

The hash value is usually huge, so the table reduces it to an index with index = h(k) mod m. [2] Lookup then proceeds:

  1. Compute h = hash(key) and i = h % m.
  2. Chaining: scan the (short) list in bucket i, comparing keys with ==.
  3. Linear probing: inspect slot i; if it holds a different key, try i+1, i+2, … (wrapping around) until the key or an empty slot is found. [3]
  4. Return the value, or report “not found”.

F.6 Deletion and tombstones

With chaining, deletion just removes the entry from its bucket’s list. With open addressing you cannot simply empty the slot: a later search that probes through it would stop early and miss keys stored beyond it. Implementations therefore mark the slot as deleted (a “dummy” or tombstone) so searches continue past it; CPython’s dict source describes slots as Unused, Dummy or Active for exactly this reason. [11] Lab 2 shows tombstones as red ✕ slots.

F.7 Resizing

As keys are added, α = n/m rises and chains or clusters grow. The remedy is to allocate a bigger table (commonly double the size) and re-insert every key, because each key’s bucket depends on m. [12] The re-insert costs Θ(n), but like dynamic-array doubling it happens rarely enough to be amortized O(1) per operation. [2]

F.8 How CPython’s dict works

Python’s dictionaries are resizable hash tables that use hash() on each key. [5] They use open addressing rather than chaining: the source code describes a probe recurrence of the form j = ((5*j) + 1) mod 2**i, perturbed by higher bits of the hash so that all hash bits eventually influence the probe sequence. [11] Since Python 3.7, iteration order is guaranteed to be insertion order. [9] Since Python 3.4 the default string and bytes hash is SipHash, adopted to resist hash-collision denial-of-service attacks. [10]

F.9 Edge cases

SituationWhat happens
Index out of rangePython raises IndexError; a negative index counts from the end, which can silently hide bugs.
Empty arraylen is 0; any index is invalid; pop() raises.
Unhashable key (list, dict, set)TypeError: unhashable type. Use a tuple or frozenset instead. [8]
Duplicate key on insertThe value is overwritten; the size does not change.
Missing keyd[k] raises KeyError; use d.get(k, default) or defaultdict.
Changing a dict while iterating itMay raise RuntimeError or skip entries. [9]
All keys collideEvery operation degrades to O(n). [6]

GMathematical foundation

G.1 The address formula

address(A[i]) = b + i · s    (0 ≤ i < n)

With b the base address and s the element size, the cost is constant regardless of i. [1]

G.2 Amortized cost of doubling (aggregate method)

Start with capacity 1 and double when full. Appending n elements triggers copies of sizes 1, 2, 4, …, 2k where 2k < n. Then

total copies = 1 + 2 + 4 + … + 2k = 2k+1 − 1 < 2n

so n appends cost fewer than n + 2n = 3n element writes: amortized O(1) per append. [1] Our Python implementation in Section I reports exactly 1 023 copies for 1 000 appends, matching 210 − 1.

Why not grow by a constant? If the array grows by a fixed amount c each time, the copies are c + 2c + 3c + … ≈ n²/(2c), which is Θ(n²) in total — Θ(n) per append on average. Geometric growth is what makes the amortized bound work.

G.3 Load factor and expected chain length

Let n keys be stored in m buckets, α = n/m. If the hash function is chosen at random from a universal family (so any two distinct keys collide with probability at most 1/m), the expected size of the chain containing a given key is

E[chain length] ≤ 1 + (n − 1)/m   =   O(1 + α)

and keeping m = Ω(n) makes α = O(1), so operations are expected O(1). MIT 6.006 gives the universal family hab(k) = ((ak + b) mod p) mod m for a prime p. [2]

G.4 Linear probing cost

Under the uniform hashing assumption, Princeton’s Algorithms gives the average number of probes for linear probing at load factor α as about

search hit ≈ ½ (1 + 1/(1−α))      search miss / insert ≈ ½ (1 + 1/(1−α)²)

At α = 0.5 that is 1.5 and 2.5 probes; at α = 0.9 it is 5.5 and 50.5 — the cost explodes as the table fills, which is why open-addressing tables must keep α well below 1. [3]

Figure G.1 · Complexity visualizationExpected probes vs load factor
chaining: 1 + αlinear probing hitlinear probing misstypical resize thresholds
  1. Curves are computed exactly from the formulas above for α from 0 to 0.95.
  2. Chaining degrades gently (a straight line); linear probing is cheap until about α ≈ 0.7, then shoots up.
Technical interpretation: the load factor, not n, controls the cost — so a hash table stays O(1) as long as it resizes to keep α bounded. [2][3]

G.5 Why the worst case is still O(n)

No fixed hash function can avoid collisions for every input: if the key universe is larger than m, some bucket receives many keys, and an adversary who knows h can choose exactly those keys. That is why MIT recommends choosing the hash function randomly from a family [2], why Python documents dict operations as O(n) in the worst case [6], and why Python adopted SipHash with a random key for strings. [10]

G.6 The birthday effect

Illustration Collisions arrive much earlier than intuition suggests. With m equally likely buckets, the probability that n keys are all distinct is ∏i<n(1 − i/m). For m = 365 this drops below ½ at n = 23 — the classic birthday paradox. Collisions are not a bug to eliminate; they are a certainty to handle.

HOperations & complexity analysis

H.1 Arrays (dynamic array, e.g. Python list)

OperationBestAverageWorstAux. space
Read / write A[i]Θ(1)Θ(1)Θ(1)O(1)
AppendΘ(1)Θ(1) amortizedΘ(n) (resize)O(1) amortized
Pop from endΘ(1)Θ(1)Θ(1)O(1)
Insert / delete at iΘ(1) (at end)Θ(n − i)Θ(n) (at front)O(1)
Search x in A (unsorted)Θ(1)Θ(n)Θ(n)O(1)
Binary search (sorted)Θ(1)Θ(log n)Θ(log n)O(1)
Slice A[a:b]Θ(b − a) — creates a copyO(b − a)

Reasoning: indexing is the address formula; append is amortized by doubling (G.2); middle insert/delete shift n − i elements; unsorted search must look at every element in the worst case (it could be last or absent). Python’s documented costs match these rows. [1][6]

H.2 Hash tables (Python dict / set)

OperationBestAverage (expected)WorstAux. space
Insert / updateΘ(1)Θ(1) amortizedΘ(n)O(1) amortized
Lookup / k in dΘ(1)Θ(1)Θ(n)O(1)
DeleteΘ(1)Θ(1)Θ(n)O(1)
Iterate all itemsΘ(n) for Python dict; a plain chaining table also visits its m buckets: Θ(n + m)O(1)
Build from n itemsΘ(n)Θ(n)Θ(n²)Θ(n)

Assumptions: the averages assume a good hash function and a load factor kept bounded by resizing. [2] The worst case is when all keys collide. [6]

Big-O, Big-Ω, Big-Θ — said precisely Dict lookup is O(n) in the worst case and Ω(1) always; its expected cost under random hashing is Θ(1). Saying “dict lookup is O(1)” is shorthand for the expected case — in interviews, say “O(1) on average”.

H.3 Time–space trade-off

Hashing spends memory to save time: a set of n items uses Θ(n) extra space (plus empty buckets kept free by the load-factor limit) to turn Θ(n) membership tests into expected Θ(1). Sorting the data in place instead costs Θ(n log n) time once and only O(1) extra space, with Θ(log n) lookups — the right choice when memory is tight or you also need order.

H.4 Theory vs Python reality

  • Python does not expose array capacity, but sys.getsizeof on a growing list reveals over-allocation: on CPython 3.11 (64-bit) the reported size changed only at lengths 1, 5, 9 and 17 while appending 20 items, so most appends needed no reallocation. [4] Exact numbers vary by version.
  • list.pop(0) is O(n); use collections.deque for queues. [6]
  • Hashing a key is not free: computing the hash of a string is proportional to its length, so “O(1) lookup” really means O(1) hash-table work plus the cost of hashing and comparing the key.

IPython implementation

I.1 A dynamic array from scratch

class DynamicArray:
    """A growable array built on a fixed-size block, like CPython's list."""

    def __init__(self):
        self._capacity = 1
        self._size = 0
        self._data = [None] * self._capacity   # the fixed-size block
        self.copies = 0                          # elements moved by resizes (for analysis)

    def __len__(self):
        return self._size

    def _check(self, i):
        if not 0 <= i < self._size:
            raise IndexError(f"index {i} out of range for size {self._size}")

    def __getitem__(self, i):                    # O(1): one address computation
        self._check(i)
        return self._data[i]

    def __setitem__(self, i, value):             # O(1)
        self._check(i)
        self._data[i] = value

    def _resize(self, new_capacity):             # O(n): copy every element
        new_data = [None] * new_capacity
        for k in range(self._size):
            new_data[k] = self._data[k]
        self.copies += self._size
        self._data = new_data
        self._capacity = new_capacity

    def append(self, value):                     # amortized O(1)
        if self._size == self._capacity:
            self._resize(2 * self._capacity)     # grow geometrically
        self._data[self._size] = value
        self._size += 1

    def insert(self, i, value):                  # O(n - i): shift right
        if not 0 <= i <= self._size:
            raise IndexError(f"insert position {i} out of range")
        if self._size == self._capacity:
            self._resize(2 * self._capacity)
        for k in range(self._size, i, -1):
            self._data[k] = self._data[k - 1]
        self._data[i] = value
        self._size += 1

    def pop(self, i=None):                       # O(n - i): shift left
        if i is None:
            i = self._size - 1
        self._check(i)
        value = self._data[i]
        for k in range(i, self._size - 1):
            self._data[k] = self._data[k + 1]
        self._data[self._size - 1] = None
        self._size -= 1
        return value

    def __repr__(self):
        items = ", ".join(repr(self._data[k]) for k in range(self._size))
        return f"DynamicArray([{items}], capacity={self._capacity})"

Line-by-line highlights

  • self._data = [None] * self._capacity simulates one fixed-size memory block; we never call append on it.
  • _check rejects negative indices on purpose — unlike Python lists — so out-of-range bugs fail loudly.
  • append doubles when full (2 * self._capacity): the geometric growth that gives amortized O(1).
  • insert walks k backwards from the end so each element is moved before its slot is overwritten.
  • pop clears the vacated last slot (None) so the old reference does not keep an object alive.

Sample run (actual output)

arr = DynamicArray()
for x in [10, 20, 30, 40, 50]:
    arr.append(x)
print(arr)            # DynamicArray([10, 20, 30, 40, 50], capacity=8)
arr.insert(1, 15)
print(arr)            # DynamicArray([10, 15, 20, 30, 40, 50], capacity=8)
print(arr.pop(0), arr)  # 10 DynamicArray([15, 20, 30, 40, 50], capacity=8)
print(arr[2], len(arr)) # 30 5
arr[9]                # IndexError: index 9 out of range for size 5

big = DynamicArray()
for x in range(1000):
    big.append(x)
print(big.copies)     # 1023  (= 1 + 2 + 4 + ... + 512 < 2 × 1000)

Dry run: insert(1, 15) on [10, 20, 30, 40, 50]

StepkAction_data[0..5]
start—size 5, capacity 8 — no resize10 20 30 40 50 _
15_data[5] = _data[4]10 20 30 40 50 50
24_data[4] = _data[3]10 20 30 40 40 50
33_data[3] = _data[2]10 20 30 30 40 50
42_data[2] = _data[1]10 20 20 30 40 50
5—_data[1] = 15; size = 610 15 20 30 40 50

Four moves for n − i = 5 − 1 = 4, exactly as Θ(n − i) predicts.

I.2 A hash map with separate chaining

class HashMap:
    """Hash table with separate chaining and automatic resizing."""

    def __init__(self, capacity=8, max_load=0.75):
        self._buckets = [[] for _ in range(capacity)]
        self._size = 0
        self._max_load = max_load

    def __len__(self):
        return self._size

    def _index(self, key):
        return hash(key) % len(self._buckets)    # hash -> bucket number

    def put(self, key, value):                   # expected O(1)
        bucket = self._buckets[self._index(key)]
        for pair in bucket:
            if pair[0] == key:                   # key already present: overwrite
                pair[1] = value
                return
        bucket.append([key, value])
        self._size += 1
        if self._size / len(self._buckets) > self._max_load:
            self._resize(2 * len(self._buckets))

    def get(self, key, default=None):            # expected O(1)
        for k, v in self._buckets[self._index(key)]:
            if k == key:
                return v
        return default

    def __contains__(self, key):
        sentinel = object()
        return self.get(key, sentinel) is not sentinel

    def remove(self, key):                       # expected O(1)
        bucket = self._buckets[self._index(key)]
        for pos, (k, _) in enumerate(bucket):
            if k == key:
                bucket.pop(pos)
                self._size -= 1
                return
        raise KeyError(key)

    def _resize(self, new_capacity):             # O(n), rare
        old = self._buckets
        self._buckets = [[] for _ in range(new_capacity)]
        for bucket in old:
            for k, v in bucket:
                self._buckets[self._index(k)].append([k, v])

    def load_factor(self):
        return self._size / len(self._buckets)

    def capacity(self):
        return len(self._buckets)

Line-by-line highlights

  • [[] for _ in range(capacity)] creates separate lists. Writing [[]] * capacity would make every bucket the same list (Section L). [21]
  • _index uses Python’s built-in hash(), which already satisfies “equal keys → equal hashes”. [7]
  • put compares with == inside the bucket: equal hashes do not imply equal keys.
  • __contains__ uses a private sentinel object so that a stored value of None still counts as present.
  • _resize recomputes every index because hash(k) % m changes when m changes.

Sample run (actual output)

m = HashMap(capacity=4)
for k, v in [("apple", 3), ("banana", 5), ("cherry", 7), ("apple", 4)]:
    m.put(k, v)
print(len(m), m.get("apple"), m.get("grape", 0), "banana" in m)   # 3 4 0 True
print(m.capacity(), m.load_factor())                              # 4 0.75
m.remove("banana")
print(len(m), "banana" in m)                                      # 2 False
m.remove("banana")                                                # KeyError: 'banana'

Note that the 4th put overwrote "apple" rather than adding a 4th entry, and that α = 3/4 = 0.75 did not exceed max_load, so no resize happened. Which bucket each word lands in varies between runs because Python randomises string hashes. [10]

I.3 Built-in Python alternatives

NeedUseNotes
Ordered sequence, index accesslistDynamic array of references. [4]
Key → valuedictHash table; insertion-ordered since 3.7. [5][9]
Membership / de-duplicationset, frozensetHash table of keys only; frozenset is hashable.
Countingcollections.Counterdict subclass for counting hashable objects; most_common(k). [19]
Groupingcollections.defaultdict(list)Missing keys start as an empty list.
Queue (both ends)collections.dequeO(1) at both ends, unlike list.pop(0). [6]
Typed numeric arraysarray.array, NumPyStore raw numbers contiguously, not references.

I.4 Comparing the implementations

Our classes are for understanding, not production: the built-ins are implemented in C, use open addressing with a tuned probe sequence (dict/set) and over-allocation heuristics (list), and are many times faster. [11][4] Asymptotically they match: our DynamicArray and list both give O(1) indexing and amortized O(1) append; our HashMap and dict both give expected O(1) operations with O(n) worst case.

JReal-world applications

AreaHow arrays / hashing are used
Programming languagesPython stores most namespaces — module globals, class attributes, instance attributes — as dictionaries, so every global-name lookup is a hash lookup. [18]
DatabasesPostgreSQL offers hash indexes, which support only equality (=) lookups — exactly the trade-off of a hash table versus an ordered B-tree. [17]
Distributed systemsConsistent hashing assigns keys to servers so that resizing the cluster remaps only about n/m keys on average instead of nearly all of them. [16]
Web securityBecause a predictable hash lets attackers force collisions and O(n) behaviour, Python switched string hashing to SipHash. [10]
Caches & backendsIllustration Session stores, memoisation (functools.lru_cache), rate limiters and de-duplication of events all reduce to “key → value in O(1)”.
Search & storageBloom filters (hash-based bit arrays) answer “definitely not present / maybe present” with no false negatives, letting systems skip expensive disk reads. [15]
Everything numericIllustration Images, audio buffers, matrices and network packets are arrays, because contiguous layout gives O(1) indexing and fast sequential scans.

KComparison with alternatives

StructureAccess by indexFind by keyInsert / deleteKeeps order?Choose when…
Array / listO(1)O(n)O(1) end, O(n) middleInsertion orderYou access by position or scan everything.
Sorted arrayO(1)O(log n)O(n)SortedData is mostly static and you need ranges or order.
Linked listO(n)O(n)O(1) at a known nodeInsertion orderFrequent splicing at known positions.
Hash table—O(1) avg, O(n) worstO(1) avgNo sorted orderFast membership, counting, grouping by key.
Balanced BSTO(log n) (augmented)O(log n)O(log n)SortedYou need min/max, ranges, or predecessor/successor.

Sources for the costs: MIT 6.006 compares array, linked-list and dynamic-array sequences [1] and hashing versus comparison-based sets [2].

Figure K.1 · Comparison diagramWhich structure should I reach for?
questionanswer pathrecommended structure
Technical interpretation: hash tables win whenever the question is “exactly this key?”; they lose whenever the question involves order (“smallest”, “next”, “between”).
When to avoid hashing Avoid hash tables when you need sorted iteration or range queries, when keys are small dense integers (a plain array is simpler and faster), when worst-case latency guarantees matter more than averages, or when memory is extremely tight.

LCommon mistakes & misconceptions

L.1 Hidden O(n) inside a loop

✗ Wrong — O(n²)
def has_dup(nums):
    seen = []
    for x in nums:
        if x in seen:      # O(n) scan
            return True
        seen.append(x)
    return False
✓ Correct — O(n) expected
def has_dup(nums):
    seen = set()
    for x in nums:
        if x in seen:      # O(1) average
            return True
        seen.add(x)
    return False

x in list is O(n) but x in set is O(1) on average. [6]

L.2 Aliased rows with *

✗ Wrong
grid = [[0] * 3] * 2
grid[0][0] = 9
print(grid)   # [[9, 0, 0], [9, 0, 0]]
✓ Correct
grid = [[0] * 3 for _ in range(2)]
grid[0][0] = 9
print(grid)   # [[9, 0, 0], [0, 0, 0]]

s * n does not copy the items; it references the same inner list multiple times. [21][20]

L.3 Unhashable keys

✗ Wrong
seen = {}
seen[[1, 2]] = "x"
# TypeError: unhashable type: 'list'
✓ Correct
seen = {}
seen[(1, 2)] = "x"          # tuple is hashable
seen[frozenset({1, 2})] = "y"

Lists and dicts are mutable and therefore not hashable. [8] Likewise, a class that defines __eq__ without __hash__ becomes unhashable, because Python sets its __hash__ to None. [7]

L.4 Mutating a dict while iterating it

✗ Wrong
for k in d:
    if d[k] == 0:
        del d[k]
# RuntimeError: dictionary changed
# size during iteration
✓ Correct
for k in list(d):          # iterate a copy
    if d[k] == 0:
        del d[k]
# or: d = {k: v for k, v in d.items() if v}

Adding or deleting entries during iteration may raise RuntimeError or skip entries. [9]

L.5 Complexity misconceptions

  • “Dict lookup is always O(1).” It is O(1) on average; the worst case is O(n). [6]
  • “Append is O(1) every time.” It is amortized O(1); an individual append can be O(n). [1]
  • “Slicing is free.” A[a:b] copies b − a references. [6]
  • “Hashing a string is O(1).” Computing it is proportional to the string’s length.
  • list.pop(0) in a BFS loop silently makes it O(n²); use deque.popleft().

L.6 Boundary errors and interview slips

  • Off-by-one: valid indices are 0 … n−1; range(n) excludes n.
  • Two Sum: inserting the current number before checking lets an element pair with itself (e.g. target 6, nums [3]).
  • Forgetting to state space: a hash-based O(n)-time solution usually uses O(n) extra space — say so.
  • Using d[k] += 1 on a plain dict without initialising — use Counter, defaultdict(int) or d.get(k, 0) + 1.

MInterview preparation

M.1 The five hashing patterns

PatternIdeaTypical problems
Seen-setRemember what you have visited; check membership in O(1).Contains Duplicate, Longest Consecutive Sequence
Complement lookupFor each x, ask whether the partner target − x was already seen.Two Sum and variants
Frequency countCount with Counter; compare or rank counts.Valid Anagram, Top K Frequent
Canonical keyMap each item to a normal form; group by it.Group Anagrams, Valid Sudoku
Prefix sum + hash mapCount earlier prefixes equal to running − k.Subarray Sum Equals K — see Chapter 03 · Prefix Sum

M.2 Common interview questions

  • Why is array indexing O(1) but linked-list indexing O(n)?
  • How does a dynamic array grow, and why is append amortized O(1)?
  • What is a collision? Compare chaining and open addressing.
  • What is the load factor and what happens when it gets too high?
  • Why must dictionary keys be immutable/hashable?
  • When would you choose a balanced BST over a hash table?

M.3 Coding exercises

1. Contains Duplicate EASY

LeetCode 217 — return true if any value appears at least twice.

HintSeen-set: stop as soon as you meet a value already in the set.
Solution
def contains_duplicate(nums):
    seen = set()
    for x in nums:
        if x in seen:
            return True
        seen.add(x)
    return False
# contains_duplicate([1, 2, 3, 1]) -> True ; [1, 2, 3, 4] -> False

Time O(n) expected, space O(n). Alternative: sort and compare neighbours — O(n log n) time, O(1) extra space.

2. Valid Anagram EASY

LeetCode 242 — are two strings rearrangements of each other?

HintTwo strings are anagrams exactly when their letter counts are equal.
Solution
from collections import Counter

def is_anagram(s, t):
    return len(s) == len(t) and Counter(s) == Counter(t)

Time O(n), space O(k) for k distinct characters.

3. Two Sum EASY

LeetCode 1 — indices of two numbers adding up to target.

HintComplement lookup: check for target − x before storing x. Lab 3 animates this.
Solution
def two_sum(nums, target):
    index_of = {}                      # value -> index
    for i, x in enumerate(nums):
        need = target - x
        if need in index_of:
            return [index_of[need], i]
        index_of[x] = i
    return []
# two_sum([2, 7, 11, 15], 9) -> [0, 1] ; two_sum([3, 2, 4], 6) -> [1, 2]

Time O(n) expected, space O(n). Brute force over all pairs is O(n²).

4. Group Anagrams MEDIUM

LeetCode 49

HintCanonical key: the sorted letters of a word are the same for all its anagrams. Lab 4 animates this.
Solution
from collections import defaultdict

def group_anagrams(words):
    groups = defaultdict(list)
    for w in words:
        groups["".join(sorted(w))].append(w)   # canonical key
    return list(groups.values())
# ["eat","tea","tan","ate","nat","bat"] -> [['eat','tea','ate'], ['tan','nat'], ['bat']]

Time O(n · k log k) for n words of length ≤ k. Using a 26-count tuple as the key makes it O(n · k).

5. Top K Frequent Elements MEDIUM

LeetCode 347

HintCount, then bucket by frequency: a frequency is between 1 and n, so an array of n + 1 buckets avoids sorting.
Solution
from collections import Counter

def top_k_frequent(nums, k):
    count = Counter(nums)
    buckets = [[] for _ in range(len(nums) + 1)]   # index = frequency
    for x, c in count.items():
        buckets[c].append(x)
    out = []
    for c in range(len(buckets) - 1, 0, -1):
        for x in buckets[c]:
            out.append(x)
            if len(out) == k:
                return out
    return out
# top_k_frequent([1, 1, 1, 2, 2, 3], 2) -> [1, 2]

Time O(n), space O(n). Counter(nums).most_common(k) is the one-liner (O(n log k)). [19]

6. Product of Array Except Self MEDIUM

LeetCode 238 — without division.

HintAnswer[i] = (product of everything left of i) × (product of everything right of i). Two passes.
Solution
def product_except_self(nums):
    n = len(nums)
    out = [1] * n
    left = 1
    for i in range(n):
        out[i] = left
        left *= nums[i]
    right = 1
    for i in range(n - 1, -1, -1):
        out[i] *= right
        right *= nums[i]
    return out
# product_except_self([1, 2, 3, 4]) -> [24, 12, 8, 6]

Time O(n), O(1) extra space besides the output. A pure array pattern — no hashing needed.

7. Longest Consecutive Sequence MEDIUM

LeetCode 128 — in O(n).

HintPut everything in a set. Only start counting from numbers x where x − 1 is not in the set.
Solution
def longest_consecutive(nums):
    s = set(nums)
    best = 0
    for x in s:
        if x - 1 not in s:             # x starts a run
            length = 1
            while x + length in s:
                length += 1
            best = max(best, length)
    return best
# longest_consecutive([100, 4, 200, 1, 3, 2]) -> 4

Each number is visited by a while loop at most once across all starts, so the total is O(n) expected (amortized argument).

8. First Missing Positive HARD

LeetCode 41 — O(n) time and O(1) extra space.

HintUse the array itself as the hash table: value v belongs at index v − 1. Swap values into place.
Solution
def first_missing_positive(nums):
    n = len(nums)
    for i in range(n):
        while 1 <= nums[i] <= n and nums[nums[i] - 1] != nums[i]:
            j = nums[i] - 1
            nums[i], nums[j] = nums[j], nums[i]
    for i in range(n):
        if nums[i] != i + 1:
            return i + 1
    return n + 1
# first_missing_positive([3, 4, -1, 1]) -> 2 ; [7, 8, 9] -> 1

Each swap places one value permanently, so there are at most n swaps: O(n) time, O(1) extra space. This “index as hash” trick is the bridge between arrays and hashing.

More practice: Valid Sudoku (36) MEDIUM — canonical keys for rows, columns and boxes; Subarray Sum Equals K (560) MEDIUM — prefix sum + hash map.

★Practice problems

Start with plain array and string traversal, then switch to sets and dictionaries. For every hashing problem, also say what the brute-force version would cost. There are 48 problems, grouped by level and topic: 45 easy and 3 medium. Each link opens the problem on the platform where you can submit and test your solution. Tick a problem when you have solved it, and use “My solution” to save your code, approach, complexity and notes to revise later.

Level
Difficulty
0 / 48 solved
Saved in this browser

Beginner37 problems

No algorithm knowledge needed — loops, conditions and indexing.

Array Operations

Traverse, count, reverse and rotate with simple loops and index arithmetic.

  1. Array or List Traversal⤢EASYGeeksforGeeks
  2. Array Search⤢EASYGeeksforGeeks
  3. Mean or Average of Array⤢EASYGeeksforGeeks
  4. Maximum and Minimum in an Array⤢EASYGeeksforGeeks
  5. Count Odd and Even⤢EASYGeeksforGeeks
  6. Count Occurrences in Sorted⤢EASYGeeksforGeeks
  7. Second Largest Element (no sorting)⤢EASYGeeksforGeeks
  8. Even Odd Sum⤢EASYGeeksforGeeks
  9. Compute Alternating Sum⤢EASYLeetCode
  10. Reverse an Array (in place)⤢EASYGeeksforGeeks
  11. Cyclically Rotate an Array by One⤢EASYGeeksforGeeks
  12. Move All Zeros to the End⤢EASYGeeksforGeeks
  13. Find All Duplicates in an Array⤢EASYLeetCode
  14. Most Frequent in Array⤢EASYGeeksforGeeks
  15. Next Round⤢EASYCodeforces
  16. Search a 2D Matrix⤢EASYLeetCode
  17. Sum of Matrix⤢EASYGeeksforGeeks
  18. Beautiful Matrix⤢EASYCodeforces
  19. Young Physicist⤢EASYCodeforces
  20. Team⤢EASYCodeforces

String Operations

Strings as arrays of characters: scan, transform and compare.

  1. Check Consonants and Vowels⤢EASYGeeksforGeeks
  2. Reverse a String⤢EASYGeeksforGeeks
  3. Check if a String is a Palindrome⤢EASYGeeksforGeeks
  4. Lowercase to Uppercase Manually⤢EASYGeeksforGeeks
  5. Toggle Case of Each Character⤢EASYGeeksforGeeks
  6. Remove Vowels⤢EASYGeeksforGeeks
  7. Count Words in String⤢EASYGeeksforGeeks
  8. Caesar Cipher⤢EASYHackerRank
  9. Way Too Long Words⤢EASYCodeforces
  10. Petya and Strings⤢EASYCodeforces
  11. Football⤢EASYCodeforces
  12. Boy or Girl⤢EASYCodeforces
  13. String Task⤢EASYCodeforces
  14. Bit++⤢EASYCodeforces
  15. Helpful Maths⤢EASYCodeforces

Basic10 problems

Direct applications of this chapter’s core idea.

Arrays

In-place edits and O(1) extra space on contiguous arrays.

  1. Largest & Smallest Element in Array⤢EASYGeeksforGeeks
  2. Move Zeroes⤢EASYLeetCode
  3. Rotate Array⤢EASYLeetCode

Strings

Character counting and comparison.

  1. Valid Anagram⤢EASYLeetCode

Hashing

Sets and dictionaries for O(1)-average membership, counting and grouping.

  1. Two Sum⤢EASYLeetCode
  2. Group Anagrams⤢MEDIUMLeetCode

Intermediate1 problem

The pattern combined with one more idea, or applied to a less obvious setup.

Array/String Operations

Medium-level array and string reasoning without a named pattern.

  1. Wiggle Subsequence⤢MEDIUMLeetCode

NAdvanced concepts

N.1 Better probe sequences

Linear probing suffers from primary clustering: one collision makes nearby collisions more likely. [13] Variants change the probe step — quadratic probing, double hashing (a second hash decides the step), and CPython’s perturbed recurrence that mixes in higher hash bits. [11] Robin Hood hashing keeps linear probing but, on collision, lets the key that is farthest from its home bucket take the slot, which evens out probe lengths. [12]

N.2 Universal hashing

Instead of one fixed hash function, pick one at random from a family where any two keys collide with probability ≤ 1/m, for example hab(k) = ((ak + b) mod p) mod m. Then no input is bad for most choices, and the expected O(1) bound holds for every input. [2]

N.3 Cuckoo hashing

Each key has two possible homes, T₁[h₁(x)] and T₂[h₂(x)]. Insertion may kick an existing key to its other home (like a cuckoo chick), but lookup checks just two cells, giving worst-case constant lookup time. It was introduced by Pagh and Rodler in 2001. [14]

N.4 Bloom filters

A Bloom filter is a bit array plus k hash functions that answers “definitely not in the set” or “possibly in the set”. False positives are possible but false negatives are not, in exchange for using far less memory than storing the keys. It was conceived by Burton Howard Bloom in 1970. [15]

N.5 Consistent hashing

With hash(k) % m, changing the number of servers m moves almost every key. Consistent hashing places keys and servers on a circle so that a resize moves only about n/m keys on average; it was introduced by Karger et al. in 1997 and underpins many distributed caches and databases. [16]

N.6 Rolling hashes and hash flooding

Polynomial rolling hashes let you update a substring’s hash in O(1) as a window slides, the basis of Rabin–Karp string search; collisions occur with probability about 1/M per comparison, so careful code uses two moduli. [22] On the defensive side, hash flooding — sending many keys that collide — turns O(1) tables into O(n) ones; PEP 456 made SipHash the default string hash in Python 3.4 to make such collisions infeasible to predict. [10]

ONotebook-ready summary

First, the whole idea on one page — copy this sheet into your notebook. The detailed revision notes follow it.

Arrays & Hashing
Jump straight to the data: by position (array) or by key (hash table)
What is an Array?

A row of equal-size slots stored next to each other in memory. Any slot can be reached directly by its index.

address(A[i]) = base + i × size

One multiply + one add → O(1) access, no searching.

What is Hashing?

A hash function turns a key into a number; the number picks a bucket in an array.

index = hash(key) % m

Equal keys must give equal hashes. Keys must be hashable (immutable).

Collisions

Two keys, same bucket. Two fixes:

  • Chaining — each bucket holds a small list.
  • Open addressing — probe the next free slot (Python’s dict).
load factor α = n / m → resize when too full
Example: Array
A

A[3] → 1000 + 3 × 8 = 1024 → read 40

Insert at front → shift everyone right: O(n). Append at end: O(1) amortized.

Example: Hash Table
★ Key Takeaway

Arrays find by position in O(1); hash tables find by key in O(1) on average. Spend memory, skip the search.

Complexity
A[i]O(1)
appendO(1)*
insert / delete middleO(n)
x in listO(n)
dict / set get, put, inO(1) avg
hash worst caseO(n)

* amortized — doubling copies < 2n

Patterns
  • 👀Seen-set → duplicates
  • 🎯Complement → Two Sum
  • 🔢Counter → anagrams, top-k
  • 🔑Canonical key → grouping
  • ➕Prefix sum + map → subarrays
Python Toolkit
  • 📋list dynamic array
  • 📖dict key → value
  • 🧺set membership
  • 🔢Counter counting
  • 🗂defaultdict(list) grouping
Watch out
  • x in list inside a loop = O(n²).
  • List keys → TypeError; use tuples.
  • [[0]*n]*m shares rows.
  • Don’t change a dict while looping it.

Detailed revision notes

1 · Definitions

  • Array: contiguous, equal-size slots; addr = base + i·size → O(1) access.
  • Dynamic array (Python list): array of references + spare capacity; doubles (grows geometrically) when full.
  • Hash table: buckets array + hash function; index = hash(k) % m; α = n/m.

2 · Core ideas

  • Position is computed, never searched.
  • Contiguity ⇒ middle insert/delete shifts Θ(n − i) items.
  • Rare Θ(n) resize, spread over many ops ⇒ amortized O(1).
  • Collisions are certain (birthday effect) — resolve by chaining or probing.

3 · Picture to draw

4 · Key properties

  • Equal keys ⇒ equal hashes (the one hard rule).
  • Mutable objects (list, dict, set) are unhashable.
  • Open addressing needs tombstones on delete; α must stay < 1.
  • Python dict: open addressing, insertion-ordered (3.7+), SipHash for str (3.4+).

5 · Complexity

OpArray / listHash (dict/set)
Access by indexO(1)—
Find by value/keyO(n)O(1) avg, O(n) worst
InsertO(1)* end, O(n) middleO(1) avg*
DeleteO(1) end, O(n) middleO(1) avg
SpaceΘ(n)Θ(n) (+ free slots)

6 · Python syntax

  • seen = set(); if x in seen: …; seen.add(x)
  • cnt = Counter(nums); cnt.most_common(k)
  • groups = defaultdict(list); groups[key].append(w)
  • d.get(k, 0) + 1 · grid = [[0]*c for _ in range(r)]

7 · Load-factor maths

  • Chaining: expected chain ≤ 1 + (n−1)/m = O(1 + α).
  • Linear probing: hit ≈ ½(1 + 1/(1−α)), miss ≈ ½(1 + 1/(1−α)²).
  • Doubling: 1 + 2 + 4 + … < 2n copies.

8 · Applications

  • Python namespaces, DB hash indexes (= only), caches, de-duplication, Bloom filters, consistent hashing.

9 · Interview takeaways

  • Brute force O(n²)? Ask: “can a set/dict remember what I’ve seen?”
  • Say “O(1) on average” and state the O(n) extra space.
  • Need order or ranges? → sort or a BST instead.
  • Values in 1..n? → the array itself can be the hash table.

PKnowledge assessment

Attempt everything before opening the answer section.

Conceptual questions

  1. Why can an array read A[i] in constant time, while a linked list cannot?
  2. Explain the difference between amortized O(1) and expected O(1), using list append and dict lookup as examples.
  3. Why does an open-addressing table need tombstones on deletion, while a chaining table does not?
  4. Why are Python lists not allowed as dictionary keys? What should you use instead?
  5. Name two situations where a balanced BST or sorted array is a better choice than a hash table.

Dry-run exercises

  1. Using the toy hash (sum of char codes mod 8) and linear probing in an 8-slot table, insert "ab", "ba", "c" in that order. Codes: a = 97, b = 98, c = 99. Which slot does each key end up in?
  2. A dynamic array starts with capacity 1 and doubles when full. How many element copies happen during the first 17 appends? What is the final capacity?
  3. Trace the one-pass Two Sum on nums = [4, 1, 5, 3], target = 8: show index_of after each step and the returned answer.

Coding problems

  1. Write first_unique_char(s) returning the index of the first non-repeating character in s, or −1. Target O(n).
  2. Write intersection_with_counts(a, b) returning the multiset intersection (each value appears min(count in a, count in b) times).
  3. Write is_isomorphic(s, t): can the characters of s be replaced one-to-one to get t? (e.g. “egg” → “add” is True, “foo” → “bar” is False.)

Practical engineering scenario

Your API receives about 50 000 events per second, each with an event_id string. Duplicates (retries) can arrive up to 10 minutes after the original and must be dropped. Memory per server is limited. Design the de-duplication: which structure(s), how you bound memory, what happens when a server restarts, and what the time cost per event is.

Answers

Conceptual answers
  1. An array’s elements are contiguous and equally sized, so the address of element i is base + i·size — one computation. A linked list’s nodes are scattered; the only way to reach node i is to follow i “next” pointers, Θ(i). [1]
  2. Amortized is a guarantee about the total cost of any sequence of operations: n appends always cost O(n) in total, even though one append may be O(n). Expected is an average over the randomness of the hash function: a single dict lookup is O(1) in expectation but could be O(n) if unlucky or attacked. [1][2]
  3. In open addressing a search stops at the first empty slot. Emptying a deleted slot could break the probe path of keys stored after it, making them unfindable; a tombstone keeps the path intact. In chaining each bucket’s list is independent, so removal just unlinks the entry. [11]
  4. Lists are mutable: if a key’s contents changed, its hash would change and the entry would sit in the wrong bucket forever. Use a tuple (or frozenset). [5][8]
  5. Any two of: you need sorted iteration; range queries (“all keys between a and b”); min/max or predecessor/successor; strict worst-case O(log n) guarantees; keys that are not hashable but are comparable.
Dry-run answers
  1. "ab" = 97+98 = 195, 195 mod 8 = 3 → slot 3. "ba" also = 195 → 3 is taken → slot 4. "c" = 99, 99 mod 8 = 3 → 3 taken, 4 taken → slot 5.
  2. Resizes happen when appending items 2, 3, 5, 9 and 17, copying 1 + 2 + 4 + 8 + 16 = 31 elements; final capacity 32. (Check: 31 < 2 × 17 = 34.)
  3. i=0, x=4: need 4, not in {} → store {4:0}. i=1, x=1: need 7, not found → {4:0, 1:1}. i=2, x=5: need 3, not found → {4:0, 1:1, 5:2}. i=3, x=3: need 5, found at 2 → return [2, 3]. (Note that at i=0, 4 + 4 = 8 but 4 must not pair with itself — checking before storing prevents it.)
Coding answers
from collections import Counter

def first_unique_char(s):
    count = Counter(s)
    for i, ch in enumerate(s):
        if count[ch] == 1:
            return i
    return -1                      # O(n) time, O(k) space

def intersection_with_counts(a, b):
    common = Counter(a) & Counter(b)   # min of counts
    return list(common.elements())     # O(len(a) + len(b))

def is_isomorphic(s, t):
    if len(s) != len(t):
        return False
    fwd, back = {}, {}
    for x, y in zip(s, t):
        if fwd.setdefault(x, y) != y or back.setdefault(y, x) != x:
            return False
    return True                    # two maps enforce one-to-one

# first_unique_char("leetcode") -> 0 ; ("aabb") -> -1
# intersection_with_counts([1, 2, 2, 1], [2, 2]) -> [2, 2]
# is_isomorphic("egg", "add") -> True ; ("foo", "bar") -> False
Engineering scenario — a model answer

About 50 000 × 600 s = 30 million IDs live in any 10-minute window. Options:

  • Exact: a hash map event_id → timestamp plus expiry. Use time buckets (e.g. one set per minute, keep the last 11) so expiry drops a whole set in O(1) per bucket instead of scanning. Cost per event: expected O(1) for the membership check and insert. Memory is proportional to 30 M IDs — tens of GB for strings in Python, so store a fixed-size 64-bit digest of the ID instead of the string, or move this state into a shared store (e.g. Redis with per-key TTL) so it also survives restarts and is shared by all servers.
  • Approximate: rotating Bloom filters (one per minute). Memory drops dramatically, and there are no false negatives — but a small false-positive rate means a few new events would be wrongly dropped, which is acceptable only if the business allows it. [15]
  • Restarts: in-process structures are lost; either accept a brief window of duplicates, persist periodically, or use the shared store.
  • Security: IDs come from clients, so use a randomised/keyed hash (Python’s default string hash already is) to avoid hash flooding. [10]

QReferences & further reading

  1. E. Demaine, J. Ku, J. Solomon, “Lecture 2: Data Structures,” MIT 6.006 Introduction to Algorithms, Spring 2020, MIT OpenCourseWare. Static and dynamic array sequences, Python list as a dynamic array, resizing, amortized analysis (Sections B, D, F, G, H, K).
  2. E. Demaine, J. Ku, J. Solomon, “Lecture 4: Hashing,” MIT 6.006, Spring 2020, MIT OpenCourseWare. Direct access, hash functions, chaining, universal hashing family, expected chain length 1 + (n−1)/m, load factor, rebuild and amortization (Sections B, C, F, G, H, N).
  3. R. Sedgewick, K. Wayne, “3.4 Hash Tables,” Algorithms, 4th ed., Princeton University. Hash function requirements, separate chaining, linear probing, load factor, probe-count formulas under uniform hashing (Sections B, D, F, G).
  4. Python Software Foundation, “How are lists implemented in CPython?”, Design and History FAQ. Lists are variable-length arrays of references; size-independent indexing; over-allocation on growth (Sections D, F, H, I).
  5. Python Software Foundation, “How are dictionaries implemented in CPython?”, Design and History FAQ. Dicts as resizable hash tables using hash(); why keys must be immutable (Sections B, F, I, P).
  6. Python Software Foundation, “Time complexity of operations on built-in types”, Python 3 documentation. Costs of list insert/pop O(n−k), append amortized O(1), x in list O(n), dict/set average O(1) and worst O(n), slicing (Sections C, D, F, H, L).
  7. Python Software Foundation, object.__hash__, Python Language Reference — Data model. Equal objects must have equal hashes; overriding __eq__ without __hash__ makes a class unhashable (Sections B, F, I, L).
  8. Python Software Foundation, “hashable,” Glossary. Definition of hashable; mutable containers are not hashable (Sections F, L, P).
  9. Python Software Foundation, “Mapping Types — dict,” Built-in Types. Insertion order guaranteed since 3.7; modifying during iteration may raise RuntimeError (Sections F, I, L).
  10. C. Heimes, “PEP 456 – Secure and interchangeable hash algorithm,” Python Enhancement Proposals, final for Python 3.4. SipHash as default str/bytes hash; motivation of hash-collision DoS (Sections F, G, I, J, N, P).
  11. CPython developers, Objects/dictobject.c, CPython source code (GitHub). Open addressing, Unused/Dummy/Active slot states, probe recurrence and PERTURB_SHIFT (Sections F, I, N, P).
  12. Wikipedia contributors, “Hash table” (secondary overview, cross-checked with [2], [3]). Luhn’s 1953 IBM memo, load factor definition, resizing by doubling, Robin Hood hashing (Sections B, F, N).
  13. Wikipedia contributors, “Linear probing” (secondary; cross-checked with [3]). Knuth’s 1963 analysis; primary clustering (Sections B, D, N).
  14. Wikipedia contributors, “Cuckoo hashing” (secondary). Pagh & Rodler 2001; two-location lookup with worst-case O(1) (Sections B, N).
  15. Wikipedia contributors, “Bloom filter” (secondary). Bloom 1970; false positives possible, no false negatives (Sections B, J, N, P).
  16. Wikipedia contributors, “Consistent hashing” (secondary). Karger et al. 1997; only about n/m keys remapped on resize (Sections B, J, N).
  17. PostgreSQL Global Development Group, “Hash Indexes,” PostgreSQL documentation. Hash indexes support only the = operator (Section J).
  18. Python Software Foundation, “Python Scopes and Namespaces,” The Python Tutorial §9.2. Most namespaces are implemented as dictionaries (Sections B, J).
  19. Python Software Foundation, collections.Counter, Python 3 documentation. dict subclass for counting hashable objects; most_common (Sections I, M).
  20. Python Software Foundation, “How do I create a multidimensional list?”, Programming FAQ. [[x]*n]*m creates references to the same row (Section L).
  21. Python Software Foundation, “Common Sequence Operations,” Built-in Types, note 2. s * n references items rather than copying them (Sections I, L).
  22. CP-Algorithms, “String Hashing”. Polynomial rolling hash; collision probability and double hashing (Sections F, N).

Practice problem sources

LeetCode problems 1, 36, 41, 49, 128, 217, 238, 242, 347 and 560 are linked at their point of use in Section M. Problem statements are owned by their respective sites.