DSA Interview Question

What is a hash table and how does it work?

Updated 2026-08-16 · Beginner friendly
Quick answer

A hash table stores key and value pairs and gives near constant time lookups. It uses a hash function to turn a key into an array index, then stores the value at that index. When two keys map to the same index, that is a collision, which is handled by methods like chaining or open addressing. On average operations are O(1).

Key takeaways
  • A hash table stores key and value pairs and gives near constant time lookups on average.
  • A hash function turns a key into an array index where the value is stored.
  • Collisions, where two keys map to the same index, are handled by chaining or open addressing.

The idea behind the speed

Instead of scanning a list to find a key, a hash table computes exactly where the value should be using a hash function. That is why looking up a key is usually as fast as reading one array slot.

// unordered_map is a hash table
unordered_map<string, int> phone;
phone["Asha"] = 99999;        // store
cout << phone["Asha"];        // fast lookup
// HashMap is a hash table
Map<String, Integer> phone = new HashMap<>();
phone.put("Asha", 99999);     // store
System.out.println(phone.get("Asha"));  // fast lookup
# Python dict is a hash table
phone = {}
phone["Asha"] = 99999      # store
print(phone["Asha"])       # fast lookup

Collisions

Different keys can hash to the same index. This is handled in two common ways. Chaining stores a small list at each index, and open addressing looks for the next free slot. Good hash functions keep collisions rare.

In the interview

The classic follow up is the worst case. Say lookups are O(1) on average but O(n) in the worst case if many keys collide, and that a good hash function and resizing keep this rare. This balance of average and worst case answers wins points.

Frequently asked questions

What is the worst case time for a hash table lookup?

It is O(n), which happens when many keys collide into the same slot. A good hash function and resizing keep this rare, so the average stays O(1).

What is the difference between a hash map and a hash set?

A hash map stores key and value pairs, while a hash set stores only unique keys. Both use hashing for fast membership checks.

Want the full DSA guide?

Read every DSA concept with notes, diagrams, and code in one place. Track your progress as you go.

Open the DSA guide All DSA questions