Pairs Whose Sum Is a Target

medium array two pointers hash map

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.

Inputnums = [3, 1, 3, 4, 3], k = 6
Output1
Sorted: [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;
}
Time: O(n log n) Space: O(1) beyond the sort