Maximum Number of Pairs in Array - Problem

You are given a 0-indexed integer array nums. In one operation, you may do the following:

  • Choose two integers in nums that are equal.
  • Remove both integers from nums, forming a pair.

The operation is done on nums as many times as possible.

Return a 0-indexed integer array answer of size 2 where answer[0] is the number of pairs that are formed and answer[1] is the number of leftover integers in nums after doing the operation as many times as possible.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,3,2,1,3,2,2]
Output: [3,1]
💡 Note: Form pairs: (1,1), (3,3), (2,2). This gives us 3 pairs. One element 2 is left over, so leftovers = 1.
Example 2 — All Pairs
$ Input: nums = [1,1,2,2,3,3]
Output: [3,0]
💡 Note: Form pairs: (1,1), (2,2), (3,3). All elements are paired, so 3 pairs and 0 leftovers.
Example 3 — No Pairs Possible
$ Input: nums = [0]
Output: [0,1]
💡 Note: Single element cannot form a pair. Result: 0 pairs, 1 leftover.

Constraints

  • 1 ≤ nums.length ≤ 1000
  • 0 ≤ nums[i] ≤ 1000

Visualization

Tap to expand
Maximum Number of Pairs in ArrayForm pairs from identical elements, count pairs and leftovers1321322Input: [1,3,2,1,3,2,2]Pair 1: (1,1)Pair 2: (3,3)Pair 3: (2,2)2LeftoverOutput: [3, 1]3 pairs formed, 1 element left over
Understanding the Visualization
1
Input Array
Array with potentially duplicate elements
2
Pair Formation
Match identical elements to form pairs
3
Count Results
Return [pairs_formed, elements_leftover]
Key Takeaway
🎯 Key Insight: Count frequency of each element, then for f occurrences make f÷2 pairs with f%2 leftovers
Asked in
Amazon 15 Microsoft 12 Google 8 Apple 6
30.0K Views
Medium Frequency
~8 min Avg. Time
856 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