Maximum Number of Pairs in Array - Problem
You're given a 0-indexed integer array nums and need to form as many pairs as possible using identical elements. In each operation, you can:
- Choose two identical integers from the array
- Remove both integers and form a pair
Your goal is to repeat this process until no more pairs can be formed, then return the results as an array [pairs_formed, leftover_elements].
Example: Given [1,3,2,1,3,2,2], you can form pairs (1,1), (3,3), and (2,2), leaving one 2 unpaired. Result: [3, 1]
Input & Output
example_1.py — Basic Case
$
Input:
[1,3,2,1,3,2,2]
›
Output:
[3,1]
💡 Note:
We can pair (1,1), (3,3), and one (2,2), leaving one 2 unpaired. Result: 3 pairs, 1 leftover.
example_2.py — All Pairs
$
Input:
[1,1]
›
Output:
[1,0]
💡 Note:
Perfect pairing case: we can form exactly 1 pair from the two 1's with no leftovers.
example_3.py — No Pairs
$
Input:
[0]
›
Output:
[0,1]
💡 Note:
Single element edge case: no pairs can be formed, so 0 pairs and 1 leftover element.
Constraints
- 1 ≤ nums.length ≤ 100
- 0 ≤ nums[i] ≤ 100
- Return array must have exactly 2 elements
Visualization
Tap to expand
Understanding the Visualization
1
Count sock types
Go through laundry basket and count how many of each sock type you have
2
Calculate pairs
For each sock type, pairs = count ÷ 2, singles = count % 2
3
Sum totals
Add up all pairs and all single socks across all types
Key Takeaway
🎯 Key Insight: Instead of searching for pairs element by element, count frequencies first and use the mathematical formula: pairs = count÷2, leftovers = count%2
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code