← Hash Map

Pattern Recognition Drill

#27 — Count pairs with difference k

Easy Hash Maps

The Problem

Count unique pairs where |a-b| = k.

What approach would you use?

Think about it before scrolling down.

Key Signals

Hash Map

Put all elements in a set. For each x, check if x+k is in the set. O(n).

Alt: Sorting

Sort + two pointers can also find all pairs with difference k in O(n log n).

Common Trap

Watch for k=0: need count of duplicates, not self-pairing. Use a Counter instead of a set.

← #26 #28 →