Max Number of K-Sum Pairs (LeetCode 1679): Solution and Explanation
You get an array and a target k. Repeatedly remove two numbers that add up to k, and return the largest number of removals you can make.
Intuition
Every number x can only pair with k - x, and each number can be used once. So the question is how many disjoint (x, k - x) pairs the array contains.
Sort the array and look at the smallest and largest values still available. If they add up to k, pairing them is always safe: no other choice could give more pairs.
If their sum is below k, the smallest value is hopeless. Its best partner is already the largest value left, and even that is not enough, so drop it. If the sum is above k, the largest value is hopeless for the same reason. Every comparison either forms a pair or throws one value away, so the pointers meet after at most n steps.
Approach: Sort and two pointers
- Sort
numsin ascending order. - Set
left = 0,right = n - 1andops = 0. - While
left < right, computetotal = nums[left] + nums[right]. - If
total == k, count one operation and move both pointers inward. - If
total < k, moveleftright. Otherwise moverightleft. - Return
ops.
Step-by-step example
nums = [3,1,3,4,3], k = 6
- Sorted, the array is [1,3,3,3,4]. left = 0, right = 4.
- 1 + 4 = 5 < 6, so 1 can never be paired. Move left to 1.
- 3 + 4 = 7 > 6, so 4 can never be paired. Move right to 3.
- 3 + 3 = 6, a match. ops = 1, left = 2, right = 2.
- The pointers have met, so the answer is 1. The last 3 has no partner.
Code: Python, Java, C++
1class Solution:
2 def maxOperations(self, nums: List[int], k: int) -> int:
3 nums.sort()
4 left, right = 0, len(nums) - 1
5 ops = 0
6 while left < right:
7 total = nums[left] + nums[right]
8 if total == k:
9 ops += 1
10 left += 1
11 right -= 1
12 elif total < k:
13 left += 1
14 else:
15 right -= 1
16 return ops1class Solution {
2 public int maxOperations(int[] nums, int k) {
3 Arrays.sort(nums);
4 int left = 0, right = nums.length - 1;
5 int ops = 0;
6 while (left < right) {
7 long total = (long) nums[left] + nums[right];
8 if (total == k) {
9 ops++;
10 left++;
11 right--;
12 } else if (total < k) {
13 left++;
14 } else {
15 right--;
16 }
17 }
18 return ops;
19 }
20}1class Solution {
2public:
3 int maxOperations(vector<int>& nums, int k) {
4 sort(nums.begin(), nums.end());
5 int left = 0, right = nums.size() - 1;
6 int ops = 0;
7 while (left < right) {
8 long long total = (long long)nums[left] + nums[right];
9 if (total == k) {
10 ops++;
11 left++;
12 right--;
13 } else if (total < k) {
14 left++;
15 } else {
16 right--;
17 }
18 }
19 return ops;
20 }
21};Time and space complexity
O(n log n)
Sorting dominates. The two-pointer scan afterwards is O(n), since each step moves at least one pointer.
O(1)
Only the pointers and the counter are stored, apart from the space the sort itself uses.
Other approaches
Hash map of unmatched values (time O(n), space O(n))
Scan the array once. For each x, if k - x has an unmatched count above zero, use it up and count an operation; otherwise record x as unmatched. This avoids sorting.
Count, then match counts (time O(n), space O(n))
Count every value first. For each x below k - x add min(count[x], count[k - x]), and when x equals k - x add count[x] / 2.
Common mistakes
- Counting the same element twice. When x equals k - x, one copy cannot pair with itself;
left < rightin the two-pointer loop prevents this. - Overflow in Java or C++. Two values near 10^9 add up to about 2 * 10^9, which is past the 32-bit limit, so compute the sum in a 64-bit type.
- Moving only one pointer after a match. Both numbers are removed, so both pointers must step inward.
- With the hash map, adding x to the map even after it matched. A used value must not be available again.
Frequently asked questions
Why is greedy pairing of the two ends optimal?
A value dropped by the pointers has no possible partner left, so dropping it loses nothing. When the two ends match, any optimal answer can be rearranged to use that same pair without losing a pair elsewhere.
Which is faster in practice, sorting or hashing?
The hash map approach is O(n) and avoids the sort, but it allocates a map. For 10^5 elements both are well within limits, and the sorted version uses no extra memory.
Does the order of removals matter?
No. The answer is just the number of disjoint pairs that sum to k, so any order that finds them all gives the same count.