You get a list of positive whole numbers, nums, and a number k. In one move you choose two numbers in the list that add up to exactly k and take both of them out.
Return the largest number of moves you can make. Each number can be taken out only once, though the list may hold the same value several times.
Example 1
Input: nums = [6, 1, 4, 3, 5], k = 7 Output: 2 Why: take out 6 + 1, then 4 + 3; the 5 has no partner
2 more examples and the constraints
Example 2
Input: nums = [4, 4, 4, 1], k = 8 Output: 1 Why: two of the 4s pair up; the third 4 is left alone
Example 3
Input: nums = [2, 9], k = 5 Output: 0 Why: 2 + 9 is 11, not 5
Constraints
- 1 ≤ length of nums ≤ 100,000
- 1 ≤ each number ≤ 1,000,000,000
- 1 ≤ k ≤ 1,000,000,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Sort + two pointersO(n log n)
- Hash map of waiting numbersO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 100,000 numbers | Verdict |
|---|---|---|---|
| Sort + two pointers | O(n log n) | Passes; no hashing needed | |
| Hash map of waiting numbers | O(n) | Best; one pass |
n = how many numbers are in the list.
Edge cases to test
- Half of k. With k = 8, two 4s pair with each other. Three 4s give only one move, not three.
- No pair at all. [2, 9] with k = 5 gives 0.
- One number. A list of length 1 can never make a move.
- Lopsided counts. Four 1s and one 9 with k = 10 give one move: the 9 runs out first.
- Big values. Two numbers near 1,000,000,000 add up past the int range; use a long for the sum.
Common mistakes
- Counting every pair of positions that sums to k, instead of using each number once.
- For x equal to k / 2, pairing a number with itself, so a single 4 counts as a move when k = 8.
- Adding x to the map even when it was just paired, so it gets used twice.
How to talk through it
- 1Clarify. Can values repeat? Can a number pair with itself? (No: two different positions.)
- 2Spot the partner. Each x can only pair with k − x, so greedy matching is safe.
- 3Offer the sort. Sort and walk two pointers inward: O(n log n), no extra structure.
- 4Code the one pass. Keep a count of waiting values; use up a partner if one is there, or start waiting.
- 5Test out loud. Run three 4s with k = 8, a list with no pair, and a single number.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?