Max Number of K-Sum Pairs
Problem Statement
You are given an integer array nums and an integer k.
In one operation you pick two numbers from the array whose sum is exactly k and remove both of them. A removed number can't be used again.
Return the largest number of operations you can do.
An integer array nums and an integer k.
The maximum number of operations, i.e. the most disjoint pairs that each sum to k.
Remove 1 and 4, then remove 2 and 3. Nothing is left.
Remove two of the 3s. The third 3 has no partner left, and 1 and 4 have no partners at all.
- • 1 ≤ nums.length ≤ 10^5
- • 1 ≤ nums[i] ≤ 10^9
- • 1 ≤ k ≤ 10^9
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
For each unused number, scan for an unused partner; mark both used
Sort, then pair the ends: equal → take both, too small → left++, too big → right--
If cnt[k − x] > 0, pair and decrement; else cnt[x]++
Keep a used flag for every position. For each unused nums[i], scan the rest of the array for an unused nums[j] with nums[i] + nums[j] == k. If found, mark both used and count one operation.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Arrays & Hashing translate into production architectures and low-level memory mechanics.