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 Array INPUT nums array: 1 3 2 1 3 2 2 Index: 0 1 2 3 4 5 6 Element counts: Value Count 1 2 2 3 3 2 nums = [1,3,2,1,3,2,2] ALGORITHM STEPS 1 Use HashSet Track unpaired elements 2 Iterate Array Check each element once 3 Match Logic If in set: remove + pairs++ If not: add to set 4 Return Result [pairs, set.size()] Single Pass Process: 1: set={1}, pairs=0 3: set={1,3}, pairs=0 2: set={1,3,2}, pairs=0 1: set={3,2}, pairs=1 3: set={2}, pairs=2 2: set={}, pairs=3 2: set={2}, pairs=3 FINAL RESULT Pairs Formed: 3 1 + 1 3 + 3 2 + 2 Leftover: 1 2 Output: [3, 1] OK - Result verified! 3 pairs + 1 leftover = 7 elements Key Insight: Using a HashSet allows O(1) lookup to check if a matching element exists. When we find a match, we remove it from the set and increment pairs. This single-pass approach achieves O(n) time complexity. The final set size gives us the leftover count directly. TutorialsPoint - Maximum Number of Pairs in Array | Single Pass Optimization
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