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:
3
💡 Note:
Element 2 appears 3 times → ceil(3/3)=1 operation, element 3 appears 2 times → ceil(2/3)=1 operation, element 4 appears 3 times → ceil(3/3)=1 operation. 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:
6
💡 Note:
Element 12 appears 9 times → ceil(9/3)=3 operations. Element 14 appears 9 times → ceil(9/3)=3 operations. Total = 6 operations.
Constraints
- 2 ≤ nums.length ≤ 105
- 1 ≤ nums[i] ≤ 106
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code