Pairs Whose Sum Is a Target
Problem
Count how many disjoint pairs of values in the array sum to k. Each value may participate in at most one pair. Sort the array and use two pointers walking inward — when the sum is too small, advance the left; too big, retreat the right; equal, count and move both.
Input
nums = [3, 1, 3, 4, 3], k = 6Output
1Sorted: [1,3,3,3,4]. Pair (3, 3) sums to 6; only one such disjoint pair.
def pair_sum_k(nums, k):
nums.sort()
l, r = 0, len(nums) - 1
count = 0
while l < r:
s = nums[l] + nums[r]
if s == k:
count += 1; l += 1; r -= 1
elif s < k: l += 1
else: r -= 1
return count
function pairSumK(nums, k) {
nums.sort((a, b) => a - b);
let l = 0, r = nums.length - 1, count = 0;
while (l < r) {
const s = nums[l] + nums[r];
if (s === k) { count++; l++; r--; }
else if (s < k) l++;
else r--;
}
return count;
}
class Solution {
public int pairSumK(int[] nums, int k) {
Arrays.sort(nums);
int l = 0, r = nums.length - 1, count = 0;
while (l < r) {
int s = nums[l] + nums[r];
if (s == k) { count++; l++; r--; }
else if (s < k) l++;
else r--;
}
return count;
}
}
int pairSumK(vector<int>& nums, int k) {
sort(nums.begin(), nums.end());
int l = 0, r = (int)nums.size() - 1, count = 0;
while (l < r) {
int s = nums[l] + nums[r];
if (s == k) { count++; l++; r--; }
else if (s < k) l++;
else r--;
}
return count;
}