Learn hub

Hashing — Pay Space, Buy Time

Replace nested loops with unordered_map / unordered_set lookups.

Suno.Problembilkulsimplehai.Arraymeinnumbershain.Targetdiyahai.Doaisenumberschahiyejinkasumtargetkebarabarho.

Listen. The problem is simple. You get an array of numbers and a target. Find two numbers whose sum equals the target.

0:00 / 1:12

When to use this

  • Have I seen X?
  • Frequency counting
  • Value → index

C++ template

unordered_map<int,int> mp;
for (int i = 0; i < n; i++) {
    int need = target - nums[i];
    if (mp.count(need)) return {mp[need], i};
    mp[nums[i]] = i;
}

Dry run

Two Sum [2,7,11,15], target 9 → [0,1].

Pitfalls

  • mp[key] inserts
  • Wrong freq updates
  • map vs unordered_map

Say this in the interview

Average O(1) lookups → O(n) time, O(n) space.

Problems in this topic (8)

Each opens teach-first (animated when available), then the code panel.