← Lessons

quiz vs the machine

Silver1100

Algorithms

Hash maps: the O(1) superpower

Why a hash set turns so many O(n²) problems into O(n).

4 min read · intro · beat Silver to climb

The trick

A hash map gives average O(1) insert and lookup. That single fact collapses a huge class of "find a pair / detect a duplicate / count occurrences" problems from O(n²) to O(n).

Example: two-sum

Instead of checking every pair (O(n²)), scan once, and for each number ask the map "have I seen target − x already?" One pass, O(n).

The catch

O(1) is average, not worst case. Collisions and resizing exist, and hashing a bad key (or relying on iteration order) bites people. But for interview-scale problems, "reach for a hash map" is the highest-leverage instinct you can build.

Practice this →

Check yourself

Answer to earn rating on the learn ladder.

1. Average time complexity of a hash-map lookup?

2. How does a hash set make two-sum O(n)?