Max Number of K-Sum Pairs - Problem

You are given an integer array nums and an integer k.

In one operation, you can pick two numbers from the array whose sum equals k and remove them from the array.

Return the maximum number of operations you can perform on the array.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,2,3,4], k = 5
Output: 2
💡 Note: We can form pairs (1,4) and (2,3), both sum to 5. Total operations: 2.
Example 2 — Duplicates
$ Input: nums = [3,1,3,4,3], k = 6
Output: 1
💡 Note: We can form one pair (3,3) that sums to 6. The remaining elements [1,4,3] cannot form valid pairs.
Example 3 — No Valid Pairs
$ Input: nums = [1,1,1,1], k = 3
Output: 0
💡 Note: No two elements sum to 3 (1+1=2), so no operations possible.

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ k ≤ 109
  • 1 ≤ nums[i] ≤ 109

Visualization

Tap to expand
Max Number of K-Sum Pairs INPUT Array nums: 1 idx 0 2 idx 1 3 idx 2 4 idx 3 Target Sum k: 5 Find pairs that sum to k=5: 1 + 4 = 5 2 + 3 = 5 nums = [1, 2, 3, 4] k = 5 ALGORITHM STEPS 1 Build Frequency Map Count occurrences of each num {1:1, 2:1, 3:1, 4:1} HashMap storing num --> count 2 For each num Calculate complement = k - num 3 Check Map If complement exists, pair found 4 Update Counts Decrement both, increment ops Example Process: num=1: comp=4, found! ops=1 num=2: comp=3, found! ops=2 num=3: comp=2, count=0, skip num=4: comp=1, count=0, skip FINAL RESULT Valid K-Sum Pairs Found: Pair 1 1 + 4 = 5 Pair 2 2 + 3 = 5 Maximum Operations 2 [OK] All pairs processed! 2 operations performed Array fully consumed Key Insight: Hash Map allows O(1) lookup for complements. For each number, we check if (k - num) exists in the map. Time Complexity: O(n) - single pass through array. Space Complexity: O(n) - for the frequency map. TutorialsPoint - Max Number of K-Sum Pairs | Hash Map (Frequency Count) Approach
Asked in
Amazon 42 Facebook 38 Google 31 Microsoft 25
89.4K Views
High Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen