Minimum Array Length After Pair Removals - Problem

Given an integer array nums sorted in non-decreasing order.

You can perform the following operation any number of times:

  • Choose two indices, i and j, where nums[i] < nums[j].
  • Then, remove the elements at indices i and j from nums. The remaining elements retain their original order, and the array is re-indexed.

Return the minimum length of nums after applying the operation zero or more times.

Input & Output

Example 1 — Balanced Distribution
$ Input: nums = [1,3,2,3,1]
Output: 0
💡 Note: We can pair (1,3), (1,3), leaving element 2. Then pair another available element with 2. All elements can be paired, so minimum length is 0.
Example 2 — Dominant Element
$ Input: nums = [2,1,1,1,3,3]
Output: 1
💡 Note: Element 1 appears 3 times, others appear 1-2 times. We can pair each 1 with different elements: (1,2), (1,3), (1,3). One element 1 remains unpaired.
Example 3 — All Same Elements
$ Input: nums = [1,1,1,1]
Output: 4
💡 Note: All elements are the same (1). Since we need nums[i] < nums[j] to form a pair, no pairs can be formed. All 4 elements remain.

Constraints

  • 1 ≤ nums.length ≤ 105
  • -106 ≤ nums[i] ≤ 106
  • nums is sorted in non-decreasing order

Visualization

Tap to expand
Array Pair Removal Problem: [1,3,2,3,1]13231Sorted array with frequenciesFrequency AnalysisElement 1: 2 times, Element 2: 1 time, Element 3: 2 timesMax frequency = 2, Total = 5Formula: max(0, 2×2 - 5) = max(0, -1) = 0Result: 0 elements remain (optimal pairing possible)
Understanding the Visualization
1
Input Analysis
Array with element frequencies
2
Pairing Strategy
Most frequent element limits total pairs
3
Mathematical Result
Formula gives minimum remaining length
Key Takeaway
🎯 Key Insight: The most frequent element determines how many elements will remain unpaired, leading to a simple mathematical formula.
Asked in
Google 15 Amazon 12 Microsoft 8 Meta 6
23.4K Views
Medium Frequency
~25 min Avg. Time
892 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