InterviewPrepKit

Home / Coding / Two Pointers

Max Number of K-Sum Pairs

medium Original β†—
Solving tips
  • It's Two Sum but counting DISJOINT pairs; sort then two pointers from both ends, or one-pass hash-map of unmatched counts.
  • Two-pointer: sum==k count and move both inward, sum<k move left up (smallest can't pair with anything), sum>k move right down.
  • Hash-map version: for each x check waiting[k-x] BEFORE incrementing waiting[x], which prevents an element pairing with itself when k is even.
  • Sort+two-pointers is O(n log n) time / O(1) space; hash map is O(n) time / O(n) space. On a match move both pointers, never one.

Problem

You are given an integer array nums and an integer k. In one operation you may pick two elements of the array whose values add up to exactly k, and remove both of them from the array.

Return the maximum number of such operations you can perform. Each element can be used in at most one operation β€” once removed, it is gone.

Examples

Example 1

Input:  nums = [1, 2, 3, 4], k = 5
Output: 2

Pair (1, 4) and pair (2, 3) both sum to 5, so two operations are possible.

Example 2

Input:  nums = [3, 1, 3, 4, 3], k = 6
Output: 1

Only one pair of 3s can be removed (3 + 3 = 6); the remaining [1, 4, 3] has no pair summing to 6.

Example 3

Input:  nums = [2, 2, 2, 2], k = 4
Output: 2

The four 2s form two disjoint pairs, each summing to 4.

Constraints

  • 1 <= nums.length <= 10^5 β€” an O(n^2) pairing scan is too slow.
  • 1 <= nums[i] <= 10^9
  • 1 <= k <= 10^9

Think about it first

Hint 1 This is Two Sum, except you must count how many disjoint pairs exist, not just find one. What made Two Sum fast?
Hint 2 If the array were sorted, where would the most promising partner for the smallest element be? What can you conclude when the smallest + largest is less than `k`? Greater than `k`?
Hint 3 Sort, then put one pointer at each end. If the two values sum to `k`, count a pair and move both pointers inward; if the sum is too small the left value can never pair with anything (everything remaining is ≀ the current right), so advance `left`; if too big, retreat `right`. Alternatively, one pass with a hash map of "unmatched counts" does it without sorting.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.