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
Minimum Array Length After Pair Removals INPUT Original Array (sorted): 1 i=0 1 i=1 2 i=2 3 i=3 3 i=4 Given: nums = [1,3,2,3,1] Sorted: [1,1,2,3,3] Value Frequency: 1 --> 2 times 2 --> 1 time 3 --> 2 times n = 5 elements max_freq = 2 ALGORITHM STEPS 1 Two Pointer Setup i = 0, j = n/2 + n%2 = 3 2 Pair and Remove If nums[i] < nums[j]: pair! Round 1: 1 < 3 [OK] Round 2: 1 < 3 [OK] Round 3: 2 (no pair left) 3 Greedy Matching Small values pair with large 1 3 1 3 4 Calculate Result pairs = 2, remaining = 5-4 min_len = n - 2*pairs = 5 - 2*2 = 1 FINAL RESULT After all removals: Pair 1 removed: 1 , 3 Pair 2 removed: 1 , 3 Remaining: 2 OUTPUT 1 Min length = 1 Key Insight: Use two pointers: one in the first half, one in the second half of the sorted array. Greedy pairing ensures maximum removals. If max_freq > n/2, result = 2*max_freq - n, otherwise result = n % 2 (0 if even length, 1 if odd). Time: O(n), Space: O(1). TutorialsPoint - Minimum Array Length After Pair Removals | Greedy Optimal Pairing
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