Find pairs and duplicates in one pass by remembering what you have seen.
Use it when you must test "has this value appeared before?", or find two values that satisfy an exact relation, such as a total or a difference. Signal words: appeared before, first repeat, two values that add up to, report the positions, one pass.
Start an empty hash set, or a hash map from value to position.
Step compute what the current value needs (itself, or target - value). Look it up. If it is there, the answer is complete. Otherwise store the current value.
Stop at the first match, or when the values run out.
It does not find the closest value, or values inside a range. The lookup answers only "is this exact value here?".
Cost: O(n) time on average and O(n) space. The check of every pair costs O(n^2) time and O(1) space.
In this lesson you learn to answer "have I seen this before?" and "has my partner appeared?" in one pass. You remember what you have read, in a hash table, and look it up in one step.
A payments app settles a batch of payments every night. Your team lead brings a dispute from Finance.
Your team lead says: A merchant was charged 100 units for two payments that were meant to be separate. Which two payments in the batch add up to 100?
A batch holds 100,000 payments, and Finance opens about 300 disputes a night. Each search must be quick.
Here is a short test. Today's amounts are [40, 15, 70, 30, 55, 25], and the disputed total is 100. The answer is the positions of the two payments: 70 at position 2 and 30 at position 3.
So the task is this: find two payments whose amounts add up to a total, and report their positions, without looking at every pair.
Imagine a box of torn ticket halves. The numbers on two matching halves add up to 100. You pull the halves out one at a time.
When a half with the number 70 comes out, you know which half it needs: the half numbered 30. You do not search the whole box. You look at your board, where you pin every half you have already pulled, one spot for each number, and check the spot for 30.
If 30 is pinned there, you have a pair. If not, you pin 70 on its own spot and pull the next half.
The board is the hash table of this lesson. The number a half needs is its complement.
Like torn ticket halves: when a seventy comes out, you know its partner is a thirty, so check one spot on the board.
Before you write code, solve the test by hand. It shows how much work one dispute takes.
Solve it by hand: The refund pair, found with a map of seen values. The hand-solve sheet loads in your browser.
You write the amounts in a row. You take each payment in turn and check it against every payment after it, until a sum reaches 100.
Amounts: [40, 15, 70, 30, 55, 25]. The disputed total is 100.
| First payment | Partners checked | Checks | Result |
|---|---|---|---|
| 40, position 0 | 15, 70, 30, 55, 25 | 5 | no partner makes 100 |
| 15, position 1 | 70, 30, 55, 25 | 4 | no partner makes 100 |
| 70, position 2 | 30 | 1 | 70 + 30 = 100: found |
The search made 5 + 4 + 1 = 10 checks. If no pair had matched, it would have made all 15 checks.
Look at what grows. Six payments need up to 15 checks. A list of n payments needs up to n × (n − 1) / 2.
You turn the hand method into code.
Start with a correct version. For every payment, try every payment after it, and stop when the sum matches.
def pair_with_total(values, target):
for i in range(len(values)):
for j in range(i + 1, len(values)): # every later payment
if values[i] + values[j] == target:
return [i, j]
return [-1, -1]This is correct. It tries each pair once, so it makes up to n × (n − 1) / 2 checks: O(n^2). The team keeps it as the reference.
Now check real batches.
A real batch holds 100,000 payments, and a miss, a dispute with no pair, makes the search run to the end.
Here is the count:
So the nightly report cannot finish before the morning.
Predict the cost
Q A batch holds 100,000 payments. The first attempt tries every pair for one disputed total and finds no match. About how long does one search take at 10^8 operations a second?
Answer: C
The number of pairs is about 100,000 × 100,000 / 2, which is 5 × 10^9. At 10^8 checks a second, that is about 50 seconds for a single dispute.
The first attempt is correct, but it looks at pairs, and there are far too many pairs. Now the team looks for a way to avoid them.
Look at the row of amounts on the whiteboard.
When you read 70, you already know the partner you need. It is 30. Can we do better than checking every payment for it?
Start with a simpler question: has this value appeared before? Keep a seen-set, a hash set that holds the values read so far.
One lookup in a hash set takes one step on average, so the whole pass takes n steps and not n × n / 2.
Now the pair. For a value v and a target total t, the partner must be t - v. This is the complement of v. The complement tells you exactly which value to look for, so the question "which payment goes with this one?" becomes "has t - v been seen?"
To answer that, and to report positions, store each value with its position in a hash map. For each value:
target - value.Look first, store afterwards. The map then holds only values from earlier positions, so a value never pairs with itself.
| Position | Value | Complement (100 − value) | In the map? | Map after |
|---|---|---|---|---|
| 0 | 40 | 60 | no | 40 at 0 |
| 1 | 15 | 85 | no | 40 at 0, 15 at 1 |
| 2 | 70 | 30 | no | 40, 15, 70 at 0, 1, 2 |
| 3 | 30 | 70 | yes, at position 2 | pair found: positions 2 and 3 |
The map made 4 lookups. The pair scan made 10 checks. And a map lookup does not grow with the batch.
Exercise · Predict the output: Which two payments pair up?. The total is 10, and the lookup comes before the store. What does this print?
values = [3, 5, 7, 5, 2]
target = 10
first_at = {}
answer = [-1, -1]
for j in range(len(values)):
need = target - values[j]
if need in first_at:
answer = [first_at[need], j]
break
if values[j] not in first_at:
first_at[values[j]] = j
print(*answer)Race: Try every pair, against one look-up and one insert per value. The operation counter loads in your browser.
The race counts the work to prove that no pair makes the total, which is the worst case. At 10,000 payments the pair scan makes 49,995,000 checks. The map makes 20,000 operations, one lookup and one insert for each payment. That is about 2,500 times less, and the gap grows with n.
A seen-set answers 'have I read this before?' in one lookup, so the first repeat appears in a single pass.
For each payment, compute the complement, the total minus the amount, and look it up in the map before storing.
The amounts are [35, 50, 20, 45, 50] and the total is 100. The list holds 50 twice, and 50 is half of the total. The player stops at four steps and asks you to predict.
Dry run: Predict each step: a repeated value in the list. The step-by-step player loads in your browser.
Reading without the player? Cover the last two columns and predict them row by row.
| Position | Value | Complement | In the map? | Map after |
|---|---|---|---|---|
| 0 | 35 | 65 | no | 35 at 0 |
| 1 | 50 | 50 | no: 50 is not stored yet | 35 at 0, 50 at 1 |
| 2 | 20 | 80 | no | adds 20 at 2 |
| 3 | 45 | 55 | no | adds 45 at 3 |
| 4 | 50 | 50 | yes, at position 1 | pair found: positions 1 and 4 |
Look at position 1. The value 50 needs a 50, but the map has no 50 yet, because the look-up happens before the store. A single 50 cannot pair with itself. At position 4 the second 50 finds the first, and the pair is complete.
Here is the rule that keeps both templates correct. Every line exists to protect it.
Before position j is read, the map holds every earlier value with its first position, so a partner found in the map always sits at an earlier position.
At the start the map is empty, so the rule holds. At position j, the template looks the complement up first. If it is found, the pair is complete and the search stops.
If it is not found, the value joins the map, and the map now covers positions 0 to j. So the rule holds for position j + 1.
The pair search cannot miss a pair. Take any pair at positions a and b with a < b. When b is read, position a is already in the map, and the lookup finds it.
Use it when you must test "has this value appeared before?", or find two values that satisfy an exact relation, such as a total or a difference. Signal words: appeared before, first repeat, two values that add up to, report the positions, one pass.
Start: an empty hash set, or a hash map from value to position.
Step: compute what the current value needs (itself, or target - value). Look it up. If it is there, the answer is complete. Otherwise store the current value.
Stop: at the first match, or when the values run out.
It does not find the closest value, or values inside a range. The lookup answers only "is this exact value here?".
Cost: O(n) time on average and O(n) space. The check of every pair costs O(n^2) time and O(1) space.
def first_repeat(values):
# [1] An empty set of values seen so far.
seen = set()
for i in range(len(values)):
# [2] A value already in the set has appeared before: this is the first repeat.
if values[i] in seen:
return i
# [3] A new value joins the set.
seen.add(values[i])
# [4] No value appeared twice.
return -1public int firstRepeat(int[] values) {
// [1] An empty set of values seen so far.
java.util.HashSet<Integer> seen = new java.util.HashSet<>();
for (int i = 0; i < values.length; i++) {
// [2] A value already in the set has appeared before: this is the first repeat.
if (seen.contains(values[i])) {
return i;
}
// [3] A new value joins the set.
seen.add(values[i]);
}
// [4] No value appeared twice.
return -1;
}int firstRepeat(vector<int>& values) {
// [1] An empty set of values seen so far.
unordered_set<int> seen;
for (int i = 0; i < (int)values.size(); i++) {
// [2] A value already in the set has appeared before: this is the first repeat.
if (seen.count(values[i])) {
return i;
}
// [3] A new value joins the set.
seen.insert(values[i]);
}
// [4] No value appeared twice.
return -1;
}function firstRepeat(values) {
// [1] An empty set of values seen so far.
const seen = new Set();
for (let i = 0; i < values.length; i++) {
// [2] A value already in the set has appeared before: this is the first repeat.
if (seen.has(values[i])) {
return i;
}
// [3] A new value joins the set.
seen.add(values[i]);
}
// [4] No value appeared twice.
return -1;
}Exercise · Put it in order: The first repeated payment. Arrange the lines into a function that returns the position of the first payment id that appeared before, or -1 when every id is new.
def first_repeat(values):
seen = set()
for i in range(len(values)):
if values[i] in seen:
return i
seen.add(values[i])
return -1
seen.add(i)def pair_with_total(values, target):
# [1] A map from each value seen so far to its first position.
first_at = {}
for j in range(len(values)):
# [2] The partner that completes the total.
need = target - values[j]
# [3] If the partner appeared earlier, report both positions.
if need in first_at:
return [first_at[need], j]
# [4] Remember this value, unless an earlier copy is already stored.
if values[j] not in first_at:
first_at[values[j]] = j
# [5] No pair makes the total.
return [-1, -1]public int[] pairWithTotal(int[] values, int target) {
// [1] A map from each value seen so far to its first position.
java.util.HashMap<Integer, Integer> firstAt = new java.util.HashMap<>();
for (int j = 0; j < values.length; j++) {
// [2] The partner that completes the total.
int need = target - values[j];
// [3] If the partner appeared earlier, report both positions.
if (firstAt.containsKey(need)) {
return new int[] {firstAt.get(need), j};
}
// [4] Remember this value, unless an earlier copy is already stored.
if (!firstAt.containsKey(values[j])) {
firstAt.put(values[j], j);
}
}
// [5] No pair makes the total.
return new int[] {-1, -1};
}vector<int> pairWithTotal(vector<int>& values, int target) {
// [1] A map from each value seen so far to its first position.
unordered_map<int, int> firstAt;
for (int j = 0; j < (int)values.size(); j++) {
// [2] The partner that completes the total.
int need = target - values[j];
// [3] If the partner appeared earlier, report both positions.
if (firstAt.count(need)) {
return {firstAt[need], j};
}
// [4] Remember this value, unless an earlier copy is already stored.
if (!firstAt.count(values[j])) {
firstAt[values[j]] = j;
}
}
// [5] No pair makes the total.
return {-1, -1};
}function pairWithTotal(values, target) {
// [1] A map from each value seen so far to its first position.
const firstAt = new Map();
for (let j = 0; j < values.length; j++) {
// [2] The partner that completes the total.
const need = target - values[j];
// [3] If the partner appeared earlier, report both positions.
if (firstAt.has(need)) {
return [firstAt.get(need), j];
}
// [4] Remember this value, unless an earlier copy is already stored.
if (!firstAt.has(values[j])) {
firstAt.set(values[j], j);
}
}
// [5] No pair makes the total.
return [-1, -1];
}Rebuild the template: put its lines back in order. Loads in your browser.
Exercise · Find the bug: The first payment that never pairs. This finds two payments that add up to the total, but it misses a pair on some batches. Which line is wrong?
def pair_with_total(values, target):
first_at = {}
for j in range(1, len(values)):
need = target - values[j]
if need in first_at:
return [first_at[need], j]
if values[j] not in first_at:
first_at[values[j]] = j
return [-1, -1]The template in order: compute the complement, look it up, report on a hit, and only then store the value.
A ride-hailing app batches pickups into dispatch slots of 180 seconds. The expected waits of six queued requests are [90, 45, 150, 30, 60, 120]. Which two requests fill a slot exactly?
This is Template 2 with target = 180.
| Position | Value | Complement | In the map? | Map after |
|---|---|---|---|---|
| 0 | 90 | 90 | no: 90 is not stored yet | 90 at 0 |
| 1 | 45 | 135 | no | adds 45 at 1 |
| 2 | 150 | 30 | no | adds 150 at 2 |
| 3 | 30 | 150 | yes, at position 2 | pair found: positions 2 and 3 |
The result is [2, 3]. The pair 90 and 90 would need two 90s, and the list holds one, so the first value did not pair with itself. The search stopped at position 3 and never read the last two requests.
Real production data brings edge cases.
Before the first payment arrives, values = []. The loop never runs, and the template returns [-1, -1]: no pair. A batch with one value, [5] with target 10, also returns [-1, -1], because a single value cannot pair with itself.
For [5, 5] with target 10, the answer is [0, 1]. The first 5 is stored, and the second 5 finds it. Two copies of one value can make a pair. One copy cannot.
For [-4, 9, 4, 2] with target 0, the complement of -4 is 4, so the pair is [0, 2]. Refunds are negative amounts, so totals of zero are common. The template needs no special case, because target - value works for negative numbers too.
For [3, 3, 3] with target 6, every pair of positions works. The template reports [0, 1]: the earliest second position, and the first stored copy. Keeping the first position makes the answer the same on every run.
Exercise · Break it: Find the batch that pairs a payment with itself. This checks whether two different payments add up to the total, but it stores each value before it looks up the complement. Find a batch and a total where it gives the wrong answer.
def has_pair(values, target):
seen = set()
for value in values:
seen.add(value)
if target - value in seen:
return True
return FalseThis version stores the value in the map first, and then looks up its complement.
Counterexample: values = [5], target = 10. The bug stores 5 at position 0, looks up 5, finds itself, and returns [0, 0]. There is no pair, so the correct answer is [-1, -1].
Look first, store afterwards.
The classic bug: store a value before looking up its complement, and a single five pairs with itself to make ten.
This version stores every value at its latest position, with first_at[value] = j and no check.
Counterexample: values = [4, 1, 4, 6], target = 10. The second 4 overwrites the first, so the bug returns [2, 3]. The agreed answer uses the first copy, [0, 3], and the rule must give the same answer on every run.
Store a value only when no earlier copy is stored.
Overwriting a repeated value moves its stored position to the last copy, and the answer changes. Keep the first copy.
A tempting fix is to sort a copy of the amounts and use two pointers, as in Module 4. The pair is found, but the positions belong to the sorted list.
Counterexample: values = [40, 15, 70, 30, 55, 25], target = 100. The sorted list is [15, 25, 30, 40, 55, 70], and the bug reports [2, 5]. The positions in the original batch are [2, 3].
When the answer is positions, keep the positions with the values, as the map does.
Your team lead asks for the two payments whose total is closest to 100, or the pairs whose total is at most 100. The complement is one exact value, and here no single value is the answer.
A map cannot rank "nearly 60". Sort the amounts and use two pointers from both ends, as in Module 4 (Opposite ends). The seen-map is for an exact relation.
Your team lead brings four product changes. Each one asks what the current value needs, and whether it was seen.
A payments app wants the first payment id that repeats in a batch. For [14, 9, 21, 14, 4], the answer is position 3. This is Template 1, a seen-set (LeetCode 217: Contains Duplicate asks only whether any value repeats).
Return the positions of two payments that add up to a total. This is Template 2, and it is the most asked pair question in interviews (LeetCode 1: Two Sum).
A music streaming app wants the pairs of tracks whose durations add up to a multiple of 60 seconds. The complement is now a remainder: a track with remainder r needs a partner with remainder (60 − r) mod 60. Store a count for each remainder (LeetCode 1010: Pairs of Songs With Total Durations Divisible by 60).
An online store wants pairs of prices that differ by exactly 25 units. A price v needs a partner at v + 25 or v − 25. Look up both, and count each pair once (LeetCode 532: K-diff Pairs in an Array).
Explain it back: write the idea in your own words and get feedback.
In two or three sentences, explain to a teammate how you find two values that add up to a total in one pass. Then explain why you look the complement up before you store the value. The AI tutor checks your answer against the invariant and the key points of this lesson.
Here is how you could explain it in an interview, now that you have built it.
For each value, I compute the partner it needs, which is the total minus the value, and look for it in a map.
If the partner is in the map, I am done. If not, I store the value with its position and read on.
I look before I store, so a value cannot pair with itself. One pass, O(n) time, O(n) space.
The straightforward answer checks every pair, which is O(n^2). I can do it in one pass with a hash map.
For each value, I compute its complement: the target minus the value. That is the one partner that completes the total. I look the complement up in a map from value to position. If it is there, I return the stored position and the current one.
If it is not there, I store the current value with its position and move on. I look up before I store, so a value never pairs with itself. If the same value appears twice, I keep the first position, which gives the same answer on every run.
Each lookup is O(1) on average, so the pass is O(n) time, with O(n) space for the map. If the question asks for the closest total, or a range, a map does not help, and I would sort and use two pointers.
Checkpoint · The seen-set
Q1/3 A service reads payment ids one at a time and must report the first id that has appeared before. What does it keep?
Answer: B
A set answers "is this value here?" in one step on average. If the id is already in the set, it is the first repeat. Otherwise it is added.
Q2/3 The values are [14, 9, 21, 14, 4]. What does the seen-set template return, as the position of the first value that appeared before?
Answer: C
Positions 0, 1 and 2 hold new values, which join the set. Position 3 holds 14, which is already in the set, so the answer is 3.
Q3/3 The total is 100 and the current value is 35. Which value does the complement search look for?
Answer: C
The complement is the target minus the value: 100 - 35 = 65. Adding instead of subtracting gives 135, a common slip.
Checkpoint · The complement map
Q1/4 Why does the pair search look the complement up before it stores the current value?
Answer: B
With [5] and target 10, storing first would find 5 in the map and report a pair that does not exist. Looking first means the map holds only earlier values.
Q2/4 The values are [4, 1, 4, 6] and the target is 10. The agreed answer uses the first copy of each value. What does the template return?
Answer: B
The first 4 is stored at position 0. The second 4 does not replace it, because a value is stored only when no earlier copy exists. At position 3, the 6 needs a 4 and finds position 0.
Q3/4 The one-pass pair search is used instead of trying every pair. What does it cost?
Answer: C
One lookup and one insert for each value are O(1) on average, so the time is O(n). The map can hold every value, which is O(n) space. The speed costs memory.
Q4/4 A batch holds 100,000 payments, and the first attempt tries every pair. About how many checks does a search with no match make?
Answer: C
The number of pairs is n x (n - 1) / 2, which is about 5 x 10^9 for n = 100,000. At 10^8 checks a second, that is about 50 seconds.
Checkpoint · Where it works
Q1/3 Which question is a job for the complement map?
Answer: C
The complement is one exact value, so the map answers "is there a partner with this exact value?". Closest, at most and largest need sorted values and two pointers.
Q2/3 Track durations are in seconds, and you want pairs whose total is a multiple of 60. A track has remainder 20 when divided by 60. Which remainder must its partner have?
Answer: C
The remainders must add up to 60, or to 0 when both are 0. So the partner needs (60 - 20) mod 60 = 40. A remainder cannot be 60 or 80.
Q3/3 The values are [-4, 9, 4, 2] and the target is 0. What does the template return?
Answer: B
The complement is 0 - (-4) = 4, which is at position 2. Negative values need no special case: the subtraction and the map work on them as on any integer.
Ten questions on this lesson. Pass with 80% or more, and solve the checkpoint's two mixed problems, to open the gate to the next stretch on the Academy map. The two problems are "Four ledgers that balance" and "The farthest matching pair".
| Step | Problem | Product line | Level | What it practises |
|---|---|---|---|---|
| 1 | The first replayed request | Platform | Easy | A seen-set that returns the first value seen before |
| 2 | A refund pair for a total | Pay | Easy | The complement map and the positions of a pair |
| 3 | Track pairs that fill whole slots | Stream | Medium | The complement of a remainder, counted in one pass |
Review cards from this lesson.
Five cards from this lesson join your spaced-review deck. The first one comes back tomorrow.
Step through the idea on your own input, then build it in the lab. Runs in your browser. Step through it.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.