What is a hash table, and why is lookup constant time?
A structure that turns a key into an array index by computing a number from it, so finding an item takes roughly the same time whether the table holds ten entries or ten million.
The mechanism. A hash function takes a key of any kind and produces a fixed-size number. Reduce that number modulo the array size and you have a bucket index. Storing and retrieving both compute the same index, so lookup is one computation plus one array access — O(1) on average, regardless of size. This is the data structure behind dictionaries, maps, objects, sets and database indexes of the hash variety.
The complication: collisions. Two different keys can produce the same bucket, and by the pigeonhole principle they must eventually. Two standard resolutions:
Chaining, where each bucket holds a list of entries, searched linearly.
Open addressing, where a colliding entry is placed in another slot by a defined probing sequence.
Why "on average" matters. If many keys land in one bucket, lookup degrades towards O(n). This is a real attack — hash flooding, where crafted inputs deliberately collide to make a server's request handling quadratic — which is why language runtimes now use randomised hash seeds.
Load factor and resizing. As the table fills, collisions rise. When occupancy passes a threshold, typically around 0.7, the table allocates a larger array and rehashes everything. That single insertion is expensive; amortised over many insertions the cost per operation remains constant, which is the honest statement of the guarantee.
What a good hash function needs: speed, and distributing keys evenly so similar inputs land far apart.
The practical consequences:
Keys must be hashable and stable. Mutating an object after using it as a key puts it in the wrong bucket and makes it unfindable — a classic bug.
Order is not guaranteed by the structure, though some languages now preserve insertion order separately.
Tree-based maps are the alternative when you need ordering or range queries, at O(log n).