Sub topic 2
Why arrays are fast and what they lack
This chapter assumes you can write loops, functions, and classes in Python, that you know what indexing a list by position means, and that you can read introductory Big-O notation such as O(1) and O(n). The previous chapter described what a key-value mapping must do: store a value under a key, fetch it, and remove it. Here we look at the array, the structure that a hash table is built on, and find out exactly which part of the mapping job it does well and which part it cannot do.
Why indexing is constant time
An array is a block of consecutive memory slots, each the same size. Because the slots are the same size and sit next to each other, the computer does not need to search for slot i. It computes where slot i is:
address of slot i = base address + i * slot sizeThat is one multiplication and one addition, whatever the value of i. Reading slot 5 and reading slot 5,000,000 cost the same. This is what "constant-time access" means: the work does not grow with the number of elements.
The following code mimics the calculation. It is a model of what the hardware does, not real memory access.
BASE_ADDRESS = 1000
SLOT_SIZE = 8 # bytes per slot, as for 64-bit pointers
def slot_address(i):
return BASE_ADDRESS + i * SLOT_SIZE
for i in (0, 1, 5, 1_000_000):
print(i, slot_address(i))A Python list works this way. It keeps a contiguous array of references to objects, so items[i] is O(1). Real hardware adds caveats, such as cache effects, but they do not change the Big-O picture.
What an array does well
The following table lists the costs for a plain array of n elements.
| Operation | Cost | Why |
|---|---|---|
| Read or write by index | O(1) | Address arithmetic |
| Append at the end | O(1) amortized | Usually a free slot; occasionally the array is copied to a bigger block |
| Insert or delete in the middle | O(n) | Later elements must shift by one slot |
| Search for a value in an unsorted array | O(n) | Any slot might hold it, so each must be checked |
| Search in a sorted array | O(log n) | Binary search, but inserts must keep the order |
The important row for this tutorial is the fourth one. An array answers "what is in slot 7?" instantly. It cannot answer "which slot holds the value I care about?" without looking.
Where arrays fall short for key-value lookup
Suppose you store user records in a list and want to find the record for the user named "alice". The list does not know that names exist. It knows only positions. You are left with a scan:
import timeit
def find_by_name(records, name):
for i, (n, _) in enumerate(records):
if n == name:
return i
return -1
for size in (1_000, 10_000, 100_000):
records = [(f"user{i}", i) for i in range(size)]
target = f"user{size - 1}" # worst case: the last record
seconds = timeit.timeit(lambda: find_by_name(records, target), number=20)
print(f"{size:>7} records: {seconds / 20 * 1000:.3f} ms per lookup")The exact times depend on your machine, but each tenfold increase in records makes the lookup take roughly ten times longer. That is O(n) behavior.
Keeping the list sorted by name lets you use binary search, which is O(log n). That is much better, but two costs remain. Every insert needs a shift to keep the order, which is O(n). And you need keys that can be ordered, which not all keys can.
So the array offers two things that look unrelated to the mapping problem:
- Fast access, but only by integer position.
- Slow search by anything else.
A hash table closes this gap by turning an arbitrary key into an integer position. First, though, it is worth seeing how far the array gets on its own.
Direct addressing: using the key as the index
If your keys are already small non-negative integers, you can skip searching. Use the key as the index. This is called a direct-address table.
_MISSING = object()
class DirectAddressTable:
def __init__(self, universe_size):
self._slots = [_MISSING] * universe_size
def _check(self, key):
if not isinstance(key, int) or not 0 <= key < len(self._slots):
raise KeyError(f"key must be an int in [0, {len(self._slots)})")
def put(self, key, value):
self._check(key)
self._slots[key] = value
def get(self, key, default=None):
self._check(key)
value = self._slots[key]
return default if value is _MISSING else value
def remove(self, key):
self._check(key)
present = self._slots[key] is not _MISSING
self._slots[key] = _MISSING
return present
table = DirectAddressTable(100)
table.put(42, "answer")
print(table.get(42))
print(table.get(7, "none"))
print(table.remove(42), table.get(42))Every operation is O(1) and no key comparison is needed. There are two details worth noting:
- The sentinel
_MISSINGmarks empty slots. If the table usedNone, you could not storeNoneas a real value and tell it apart from "absent". _checkrejects negative keys on purpose. In Python,slots[-1]does not fail. It reads the last slot, so an unchecked key of-1would silently collide with keylen - 1.
Why direct addressing does not scale
Direct addressing has three limits, and each one points to something a hash table must supply.
- Huge key ranges. Say you track 500 students whose IDs run up to 9,999,999. The table needs 10 million slots. At about 8 bytes per slot in a Python list on a 64-bit system, that is roughly 80 MB to hold 500 entries. The array size is set by the range of possible keys, not by the number of keys you actually store.
- Non-integer keys. Strings, tuples, and objects are not positions. The array cannot use
"alice"as an index. - Unbounded keys. If keys can be any integer, including very large ones, no array can cover the range.
Put in terms of two numbers: let U be the size of the universe of possible keys and n the number of keys actually stored. Direct addressing needs space proportional to U. We want space proportional to n while keeping O(1) access.
The fix has two steps, and the next chapters build them:
- Convert any key into an integer with a hash function.
- Shrink that integer into a valid index for an array of about
nslots, usually with the modulo operator.
Shrinking the range has a price. Many possible keys now share few slots, so two keys will sometimes land in the same slot. That problem, collisions, is what chaining and open addressing exist to solve.
Summary of what the array gives and what it lacks
| The array provides | The mapping still needs |
|---|---|
| O(1) read and write by integer index | A way to turn any key into an integer |
| Compact, contiguous storage | Storage sized by `n`, not by the key range `U` |
| Cheap append | A rule for two keys that map to the same slot |
Exercise
A list holds 1,000,000 records sorted by integer ID, and IDs range from 0 to 999,999,999. You can afford a direct-address table of 1,000,000 slots. Explain why direct addressing with the ID as the index fails here, and name the two things you would need to add so that an array of about 1,000,000 slots could still be used.
Show answer
Using the ID as the index needs 1,000,000,000 slots, because the array size must cover the whole key range, and an ID such as 500,000,000 is outside an array of 1,000,000 slots. To keep a 1,000,000-slot array you need a function that maps any key to an integer (a hash function) and a step that shrinks that integer into the range 0 to 999,999 (for example, modulo the array size). Because up to a billion possible IDs now share a million slots, you also need a collision-handling rule for keys that land in the same slot.
Exercise
What is the cost of finding the value 77 in an unsorted array of n elements, compared with reading the element at index 77? Give both in Big-O notation and say why they differ.
Show answer
Searching for the value 77 costs O(n), because the value could be in any slot and the worst case checks every one. Reading index 77 costs O(1), because the address is computed as base + 77 * slot size without visiting other slots. The array knows positions, not contents.