Max Number of K-Sum Pairs - Problem

You have an integer array nums and a target value k. Your goal is to maximize the number of operations you can perform on the array.

In each operation, you can:

  • Pick any two numbers from the array whose sum equals k
  • Remove both numbers from the array
  • Count this as one operation

Return the maximum number of operations you can perform until no more valid pairs exist.

Example: If nums = [1,2,3,4] and k = 5, you can pair (1,4) and (2,3) for a total of 2 operations.

Input & Output

example_1.py โ€” Basic case
$ Input: nums = [1,2,3,4], k = 5
โ€บ Output: 2
๐Ÿ’ก Note: We can form pairs (1,4) and (2,3), both summing to 5. This gives us 2 operations total.
example_2.py โ€” Multiple duplicates
$ Input: nums = [3,1,3,4,3], k = 6
โ€บ Output: 1
๐Ÿ’ก Note: Only one pair (3,3) can be formed that sums to 6. Even though there are three 3's, we can only use two of them for one operation.
example_3.py โ€” No valid pairs
$ Input: nums = [1,1,1,1], k = 3
โ€บ Output: 0
๐Ÿ’ก Note: No two elements can sum to 3 since all elements are 1, and 1+1=2 โ‰  3.

Visualization

Tap to expand
๐Ÿ•บ Dance Partner Matching: Heights must sum to k=5 ๐Ÿ’ƒ1Height: 12Height: 23Height: 34Height: 4Waiting ListHeight: 1Height: 2Looking for height 2...โœ“๐ŸŽ‰ Perfect Match Found! ๐ŸŽ‰Dancer 3 (height 3) + Dancer 2 (height 2) = 5 โœจOperations Count: 1 โ†’ 2Remove both from waiting list and pair them up!๐Ÿ’ก Key Insight: Hash table allows O(1) lookup for perfect partnersโšก Optimal: O(n) time, O(n) space - process each dancer exactly once
Understanding the Visualization
1
Dancers Arrive
As each dancer arrives, we check our waiting list for their perfect height complement
2
Perfect Match Found
If the complement exists, we immediately pair them up and they start dancing
3
Join Waiting List
If no perfect partner is waiting, the dancer joins our waiting list
4
Maximize Pairs
This process ensures we form pairs as quickly as possible, maximizing the total number of dancing pairs
Key Takeaway
๐ŸŽฏ Key Insight: Instead of checking all possible pairs (O(nยฒ)), we use a hash table to instantly find perfect partners in O(1) time, achieving optimal O(n) performance.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

Single pass through array with O(1) hash map operations

n
2n
โœ“ Linear Growth
Space Complexity
O(n)

Hash map can store up to n unique elements in worst case

n
2n
โšก Linearithmic Space

Constraints

  • 1 โ‰ค nums.length โ‰ค 105
  • 1 โ‰ค nums[i] โ‰ค 109
  • 1 โ‰ค k โ‰ค 109
  • Follow-up: Can you solve this in O(n) time?
Asked in
Amazon 45 Google 38 Meta 32 Microsoft 28
89.6K 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