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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code