Many interview problems ask some version of the same question: for this element, does a matching element exist somewhere else? The first answer that comes to mind is a second loop that checks every other element. It is correct, and it is quadratic. This guide shows how to swap that inner loop for a hash map or set lookup. You will see the three shapes it takes (complements, counting, grouping by a key), trace one problem step by step, and learn how to state the trade clearly: you get linear time and pay for it with memory.
The intuition
The picture to keep in your head.
Look at what the inner loop of a nested-loop solution actually does. For element i, it scans every j to answer a question such as "is there a value equal to target - a[i]?" or "how many times have I seen this character?". It repeats that scan from scratch for every i, even though the answer depends only on values you have already walked past.
A hash set or hash map remembers those values. Instead of rescanning, you ask the map directly, and a hash lookup takes expected constant time. The scan of n elements becomes a single lookup, so n scans become n lookups: O(n²) drops to O(n).
The key habit is to ask first and store second. Walk the input once. For each element, work out what partner you need, look it up among the elements already seen, and only then add the current element to the map. Doing it in that order means every pair is found exactly once, from its later member, and an element never pairs with itself.
What you store depends on the question. A set answers "have I seen this value?". A map answers "how many times?" (value to count), "where?" (value to index) or "which ones?" (key to list). When the match is not a literal equality, transform each element into a key that all matching elements share, such as a word with its letters sorted, and look up that key instead.
The price is memory. The map can hold up to one entry per distinct element, so you go from O(1) extra space to O(n), or O(k) if values come from a fixed alphabet of size k. At 10 items nobody notices either cost. At 100,000 items the nested loop does about 5 billion comparisons, while the map does 100,000 lookups and holds at most 100,000 entries. That is the trade the interviewer wants you to name.
Step by step
Small, safe steps, with the tests passing after each.
Step 1: Write the naive version and price it
State the brute force out loud: two loops over all pairs
i < j, O(n²) time, O(1) extra space. It proves you understand the problem and gives you a baseline to improve on. Then point at the inner loop and say what question it keeps answering.Step 2: Name what the inner loop is searching for
Turn the inner loop into a lookup target. For a sum it is the complement
target - x. For a difference k it isx - kandx + k. For counting it is the element itself. For grouping it is a canonical key that every member of the group produces.Step 3: Choose the structure by what you need back
Need only yes or no: a set. Need how many: a map from value to count. Need a position: a map from value to index. Need the members: a map from key to list. If values come from a small fixed alphabet, a plain array of size k works as the map and is faster.
Step 4: Ask before you store
In the single pass, query the map for the partner first, update your answer, then insert the current element. This order counts each pair once and prevents an element from matching itself, which matters when the target partner equals the element (difference 0, or
target = 2x).Step 5: State the new cost and the memory you paid
Expected O(n) time, since each element does a constant number of hash operations. Extra space O(d), where d is the number of distinct values stored, at most n. Mention the alternative: sorting plus two pointers gives O(n log n) time with little extra memory if the interviewer cares about space.
What it costs
Time and memory, and why.
- Time
- O(n) expected, O(n²) naive
- Memory
- O(d) extra, d = distinct values (at most n)
Each of the n elements performs a fixed number of map operations: two lookups and one insert in the traced problem. Hash map operations take expected O(1), so the pass is expected O(n). The worst case for a hash table with adversarial collisions is O(n) per operation, which is why you say expected. The map stores one entry per distinct value, so extra space is O(d), between O(1) when everything repeats and O(n) when all values differ. The nested-loop version checks n(n-1)/2 pairs, which is O(n²) time and O(1) extra space.
A traced example
A small input, followed step by step.
Parcelwise loads two vans and wants shipments whose weights differ by exactly k kg so the vans stay balanced. Given weights [4, 1, 3, 5, 3] and k = 2, count the index pairs i < j with |weights[i] - weights[j]| = k.
- 1
Start: seen = {}, pairs = 0seenmaps a weight to how many earlier shipments had it. Nothing has been read yet. - 2
x = 4: seen[2] = 0, seen[6] = 0, pairs = 0; seen = {4:1}A partner would weigh 2 or 6. Neither appeared earlier, so no pairs. Store 4 after asking. - 3
x = 1: seen[-1] = 0, seen[3] = 0, pairs = 0; seen = {4:1, 1:1}No earlier 3 yet. The pair (1, 3) will be found later, from the 3's side. - 4
x = 3: seen[1] = 1, seen[5] = 0, pairs = 1; seen = {4:1, 1:1, 3:1}One earlier 1 exists, so the pair (index 1, index 2) is counted. - 5
x = 5: seen[3] = 1, seen[7] = 0, pairs = 2; seen = {4:1, 1:1, 3:1, 5:1}The earlier 3 pairs with this 5: (index 2, index 3). - 6
x = 3: seen[1] = 1, seen[5] = 1, pairs = 4; seen = {4:1, 1:1, 3:2, 5:1}This second 3 pairs with both the earlier 1 and the earlier 5. Adding counts, not just 1, is what handles duplicates correctly.
Result: pairs = 4: (1,3), (1,3), (3,5), (5,3) by index, found with 5 iterations instead of 10 pair checks.
The code
The same solution in TypeScript, Python and PHP.
// Naive: check every pair i < j. O(n^2) time, O(1) extra space.
function countPairsWithDiffNaive(weights: number[], k: number): number {
let pairs = 0;
for (let i = 0; i < weights.length; i++) {
for (let j = i + 1; j < weights.length; j++) {
if (Math.abs(weights[i] - weights[j]) === k) pairs++;
}
}
return pairs;
}
// One pass with a map. O(n) expected time, O(d) extra space. Assumes k >= 0.
function countPairsWithDiff(weights: number[], k: number): number {
// seen maps weight -> how many earlier shipments had it
const seen = new Map<number, number>();
let pairs = 0;
for (const x of weights) {
// ask before storing, so x never pairs with itself
if (k === 0) {
pairs += seen.get(x) ?? 0;
} else {
pairs += (seen.get(x - k) ?? 0) + (seen.get(x + k) ?? 0);
}
seen.set(x, (seen.get(x) ?? 0) + 1);
}
return pairs;
}
console.log(countPairsWithDiffNaive([4, 1, 3, 5, 3], 2)); // 4
console.log(countPairsWithDiff([4, 1, 3, 5, 3], 2)); // 4# Naive: check every pair i < j. O(n^2) time, O(1) extra space.
def count_pairs_with_diff_naive(weights: list[int], k: int) -> int:
pairs = 0
n = len(weights)
for i in range(n):
for j in range(i + 1, n):
if abs(weights[i] - weights[j]) == k:
pairs += 1
return pairs
# One pass with a map. O(n) expected time, O(d) extra space. Assumes k >= 0.
def count_pairs_with_diff(weights: list[int], k: int) -> int:
# seen maps weight -> how many earlier shipments had it
seen: dict[int, int] = {}
pairs = 0
for x in weights:
# ask before storing, so x never pairs with itself
if k == 0:
pairs += seen.get(x, 0)
else:
pairs += seen.get(x - k, 0) + seen.get(x + k, 0)
seen[x] = seen.get(x, 0) + 1
return pairs
print(count_pairs_with_diff_naive([4, 1, 3, 5, 3], 2)) # 4
print(count_pairs_with_diff([4, 1, 3, 5, 3], 2)) # 4<?php
// Naive: check every pair i < j. O(n^2) time, O(1) extra space.
function countPairsWithDiffNaive(array $weights, int $k): int
{
$pairs = 0;
$n = count($weights);
for ($i = 0; $i < $n; $i++) {
for ($j = $i + 1; $j < $n; $j++) {
if (abs($weights[$i] - $weights[$j]) === $k) {
$pairs++;
}
}
}
return $pairs;
}
// One pass with a map. O(n) expected time, O(d) extra space. Assumes k >= 0.
function countPairsWithDiff(array $weights, int $k): int
{
// seen maps weight -> how many earlier shipments had it
$seen = [];
$pairs = 0;
foreach ($weights as $x) {
// ask before storing, so x never pairs with itself
if ($k === 0) {
$pairs += $seen[$x] ?? 0;
} else {
$pairs += ($seen[$x - $k] ?? 0) + ($seen[$x + $k] ?? 0);
}
$seen[$x] = ($seen[$x] ?? 0) + 1;
}
return $pairs;
}
echo countPairsWithDiffNaive([4, 1, 3, 5, 3], 2), PHP_EOL; // 4
echo countPairsWithDiff([4, 1, 3, 5, 3], 2), PHP_EOL; // 4Variants
Shapes the same idea takes.
Complement lookup
When: You need two elements that combine to a target: a sum, a difference, a product, a XOR.
Compute the partner each element needs and look it up among earlier elements. Store value to index if the answer is positions, value to count if the answer is how many pairs, or just a set if any match will do. Ask before storing so the element does not match itself.
Frequency counting
When: The answer depends on how often values occur: equal multisets, first unique item, majority, most common.
One pass builds value to count, a second pass (over the input or the map) reads it. Time O(n), space O(k) for k distinct values. With a fixed small alphabet such as lowercase letters, an int array of size 26 replaces the map. Sorting both inputs also compares multisets but costs O(n log n).
Grouping by a canonical key
When: Elements belong together when they are equivalent under some rule rather than identical.
Map each element to a key that all equivalent elements share, then append it to
groups[key]. Sorting a word of length k gives a key in O(k log k), so n words cost O(n·k log k). A count signature over a fixed alphabet builds the key in O(k + alphabet). The key must be a value type: a string or tuple, not a mutable list.Set membership and intersection
When: You only need to know whether a value exists: duplicates, common items, filtering against a blocklist.
Load one collection into a set and stream the other through it. For an intersection, build the set from the smaller input to keep memory at O(min(n, m)) while time stays O(n + m). A set also deduplicates in one pass, which is often the whole fix for a slow distinct-count.
Prefix-sum complements
When: You need contiguous subarrays with a given sum, or a balance of zero, rather than pairs of single elements.
Keep a running prefix sum and a map from prefix value to how many times it occurred. A subarray ending here sums to target exactly when
prefix - targetwas seen before. Seed the map with {0: 1} so subarrays starting at index 0 count. This turns an O(n²) scan over all start and end points into O(n).
Common mistakes
What usually goes wrong and how to avoid it.
Avoid
Inserting the current element before looking up its partner.
Better
Always query first, then store. Otherwise, when the partner equals the element (difference 0, or target equal to twice the value), the element pairs with itself and inflates the answer.
Avoid
Using a set when duplicates matter.
Better
A set collapses repeated values, so the second 3 in the trace would add 1 instead of 2. If the question counts pairs or occurrences, store counts in a map and add the count.
Avoid
Checking membership with a list or array search inside the loop.
Better
x in some_list,arr.includes(x)andin_array($x, $arr)are linear scans, so the nested loop is still there, just hidden. Use a set, a dict, a Map, or PHP array keys withisset.Avoid
Using a mutable or reference-typed value as a grouping key.
Better
In JavaScript, two arrays with the same content are different Map keys, and in Python a list is not hashable. Join to a string or use a tuple for the key.
Avoid
Claiming O(1) space or ignoring the map entirely in the analysis.
Better
Say the map holds up to one entry per distinct value: O(n) in general, O(k) for a fixed alphabet. Interviewers specifically listen for whether you name the memory you traded.
Avoid
Calling hash lookups strictly O(1) in the worst case.
Better
Say expected or average O(1). Worst-case collisions can degrade operations to O(n); it rarely matters in practice, but stating it precisely shows you understand the structure.
How to recognise it
Clues in a problem statement that call for it.
- The brute force has a second loop whose only job is to find a matching element for the outer one.
- The problem says pair, two elements, complement, or adds up to.
- You need to know whether something has appeared before, or how many times.
- Two inputs are compared for shared values, duplicates or equal contents.
- Items must be bucketed when they are equivalent under a rule, such as same letters or same normalized form.
- Constraints allow n up to around 10^5 or more, which rules out O(n²).
- The order of elements does not matter for the answer, only their values and counts.
Common questions
Short answers to the usual doubts.
When should I sort instead of using a hash map?
Sort when memory is tight or the input is already sorted. Sorting plus two pointers solves pair problems in O(n log n) time with O(1) or O(log n) extra space, depending on the sort. It also gives deterministic worst-case behavior. If the problem asks for original indices, sorting loses them unless you carry them along, which pushes you back toward a map.
Is a hash lookup really constant time?
On average, yes. A good hash function spreads keys across buckets, so each lookup checks a constant expected number of entries. In the worst case many keys collide and one operation can take O(n). Say expected O(1) and expected O(n) overall; that is the precise statement interviewers want.
Set or map: how do I choose?
Ask what you need back after the lookup. A yes or no answer only needs a set. If you need a count, an index or a list of members, you need a map from the key to that data. Using a map where a set suffices wastes some memory; using a set where counts matter gives wrong answers.
How much memory does the map actually cost?
One entry per distinct key, plus the hash table's overhead for buckets and spare capacity, which is a constant factor. Asymptotically that is O(d) with d at most n. If keys come from a fixed alphabet, such as 26 letters or 256 byte values, the space is O(k) regardless of input length, and an array is cheaper than a hash map.
How should I present this in the interview?
Three sentences in order. First, the brute force and its cost: every pair, O(n²) time, O(1) space. Second, the insight: the inner loop is just searching for a specific value, so a hash map can answer it in expected O(1). Third, the trade: one pass, expected O(n) time, O(n) extra memory. Then code the one-pass version and trace a small input with a duplicate.
Now, practise it
Put it to work straight away.
Tests, exercises and problems that use what you've just read.
- Revenue per customer (like an aggregate)Solve the exercise
- Cart total with a couponSolve the exercise
- Any duplicate?Solve the problem
- Two that add up to the targetSolve the problem
- Items in commonSolve the problem
- Are they anagrams?Solve the problem
- The first character that doesn't repeatSolve the problem
- Group anagramsSolve the problem
- Improve this: unique visitorsSolve the problem