InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Two Pointers

Max Number of K-Sum Pairs

medium Original ↗ 00:00

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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug