Jaconir
Skip to lesson
easy
20 minIntern through senior

When to use. Membership, counting, pairing complements, grouping — anything that is “have I seen this?”

Complexity. Time Average O(1) get/set/delete; worst O(n) with bad collisions. Space O(n) for the table.

Who gets asked. Interns: two-sum style maps. Seniors: load factor, collision strategy, and when a sorted structure beats a map.

Prereq. Arrays and Big O.

Hash Tables: The Ultimate Dictionary

Master the data structure that powers everything from databases to caches with lightning-fast lookups.

What Is a Hash Table?

A hash table, also known as a hash map, is a data structure that stores key-value pairs. Think of it like a real-world dictionary. If you want to find the definition of the word "algorithm," you don't read the entire dictionary; you jump directly to the "A" section. Hash tables work on a similar principle, providing incredibly fast access to data.

This magic is achieved through two main components:

  • An Array: This is the underlying storage, often called a "bucket array".
  • A Hash Function: This is a special function that takes a key (like the word "algorithm") and converts it into an index (a number) that corresponds to a bucket in the array.

When you want to store a value, the hash table uses the hash function to figure out which bucket to put it in. When you want to retrieve it, it uses the same hash function on the key to know exactly where to look. This direct lookup is why, on average, hash table operations (insertion, deletion, and search) take constant time, or O(1). Worst case is O(n) with pathological collisions — say that in a senior round. Intern screens use maps for complements and counts; pair that with two pointers when the array is already sorted.

Handling Collisions

What happens if the hash function generates the same index for two different keys? This is called a **collision**, and it's a natural part of how hash tables work. The most common way to handle this is a technique called **chaining**. Instead of storing a single value in each bucket, the bucket stores a linked list of all the key-value pairs that hashed to that index. When a collision occurs, the new pair is simply added to the end of the list.

Interactive Hash Table
Insert, lookup, and delete key-value pairs to see how a hash table works, including collisions.
0
empty
1
empty
2
empty
3
empty
4
empty
5
empty
6
empty
Quick Quiz: Test Your Knowledge

What is the primary purpose of a hash function in a hash table?

What is the average time complexity for insertion, deletion, and lookup in a well-designed hash table?

What happens when a hash function generates the same index for two different keys?

Coding Challenge
Numbers and a target. Return two distinct indices whose values add to the target. One pass with a complement map. Average O(n) time, O(n) space.

Saved in this browser. No account.