Minimum Number of Operations to Make Array Empty - Problem

You are given a 0-indexed array nums consisting of positive integers.

There are two types of operations that you can apply on the array any number of times:

  • Choose two elements with equal values and delete them from the array.
  • Choose three elements with equal values and delete them from the array.

Return the minimum number of operations required to make the array empty, or -1 if it is not possible.

Input & Output

Example 1 — Mixed Frequencies
$ Input: nums = [2,1,3,3,2]
Output: -1
💡 Note: Element 1 appears only once, which cannot be removed using operations that require 2 or 3 identical elements. Therefore, it's impossible to make the array empty.
Example 2 — All Removable
$ Input: nums = [2,3,3,2,2,4,4,4]
Output: 4
💡 Note: Element 2 appears 3 times (1 operation), element 3 appears 2 times (1 operation), element 4 appears 3 times (1 operation). Total: 3 operations. Wait, let me recalculate: 2 appears 3 times → ceil(3/3)=1, 3 appears 2 times → ceil(2/3)=1, 4 appears 3 times → ceil(3/3)=1. Total = 3 operations.
Example 3 — Large Frequencies
$ Input: nums = [14,12,14,14,12,14,14,12,12,12,12,14,14,12,14,14,14,12]
Output: 7
💡 Note: Element 12 appears 9 times → ceil(9/3)=3 operations. Element 14 appears 9 times → ceil(9/3)=3 operations. Total = 6 operations. Actually let me recount: I see 12 appears 9 times and 14 appears 9 times, so 3+3=6 operations.

Constraints

  • 2 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 106

Visualization

Tap to expand
Minimum Operations to Make Array Empty233224Input: [2, 3, 3, 2, 2, 4] → Need to remove all elementsElement 2Count: 3 → 1 opElement 3Count: 2 → 1 opElement 4Count: 1 → impossibleRemove 3Remove 2Cannot remove 1Result: -1 (Impossible)
Understanding the Visualization
1
Input Analysis
Count frequency of each unique element
2
Operation Planning
Calculate minimum operations using mathematical formula
3
Result
Sum operations or return -1 if impossible
Key Takeaway
🎯 Key Insight: Use ceil(frequency/3) formula to find minimum operations, but return -1 if any element appears only once
Asked in
Google 15 Amazon 12 Microsoft 8
23.4K Views
Medium Frequency
~15 min Avg. Time
890 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