← Hash Maps

Drill #27 — Count pairs with difference k

Easy Set Lookup Hash Maps

In plain English: Count how many unique pairs of numbers in an array differ by exactly k.

A set gives O(1) membership testing — for each x, just check if x+k exists.

Prompt

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

Try to write it from scratch before scrolling down.

Solution

def count_pairs_diff(a, k):
    s = set(a)  # O(1) lookup for complement
    count = 0
    for x in s:
        if x + k in s:  # only check x+k, not x-k, to avoid double counting
            count += 1
    return count

# Test: count_pairs_diff([1,5,3,4,2], 2) == 3
O(n) time · O(n) space

Related Micro Drills

← Drill #26 Drill #28 →