Minimum Number of Operations to Make Array Empty - Problem
Problem Overview: You have an array of positive integers and need to completely empty it using two types of operations:

Operation 1: Remove any 2 elements with the same value
Operation 2: Remove any 3 elements with the same value

Your goal is to find the minimum number of operations needed to make the array empty. If it's impossible to empty the array, return -1.

For example, with array [2,3,3,2,2,4,2,3,4], you have:
• Four 2's → can be removed as 3+1 (2 operations)
• Three 3's → can be removed as 3 (1 operation)
• Two 4's → can be removed as 2 (1 operation)

Total: 4 operations to empty the array.

Input & Output

example_1.py — Basic case
$ Input: [2,3,3,2,2,4,2,3,4]
Output: 4
💡 Note: We have: 4 twos (can remove as 2+2: 2 operations), 3 threes (can remove as 3: 1 operation), 2 fours (can remove as 2: 1 operation). Total: 4 operations.
example_2.py — Impossible case
$ Input: [2,1,2,2,3,3]
Output: -1
💡 Note: Element 1 appears only once. Since we can only remove 2 or 3 identical elements at a time, it's impossible to remove the single 1.
example_3.py — Edge case with remainder 1
$ Input: [2,2,2,2,2]
Output: 2
💡 Note: We have 5 twos. Optimal strategy is to remove 2+2=4 elements (2 operations) rather than 3+1+1 which would be impossible. Formula: (5+2)÷3 = 2.

Constraints

  • 2 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 106
  • All elements are positive integers

Visualization

Tap to expand
🍕 Pizza Cleanup StrategyPepperoni: 4 slicesStrategy: 2 + 2Trips needed: 2Veggie: 3 slicesStrategy: 3Trips needed: 1Cheese: 2 slicesStrategy: 2Trips needed: 1🎯Total: 4 trips⚠️ What if there was only 1 Hawaiian slice?Impossible! Can't carry single slice → Return -1
Understanding the Visualization
1
Count Slice Types
First, count how many slices of each type you have
2
Apply Strategy
For each type, calculate minimum trips using the formula (count + 2) ÷ 3
3
Handle Edge Cases
If any slice type has only 1 slice, cleanup is impossible
Key Takeaway
🎯 Key Insight: The formula (count + 2) ÷ 3 automatically handles the optimal strategy: use groups of 3 when possible, but when remainder is 1, it's better to use two groups of 2 rather than leaving a single unusable item.
Asked in
Google 45 Amazon 38 Meta 25 Microsoft 22
32.5K Views
Medium-High Frequency
~18 min Avg. Time
1.2K 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