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
Minimum Operations to Make Array Empty INPUT nums = [2, 1, 3, 3, 2] 2 1 3 3 2 0 1 2 3 4 Frequency Count: Value: 1 Count: 1 Value: 2 Count: 2 Value: 3 Count: 2 Operations Allowed: Delete 2 equal elements Delete 3 equal elements Goal: Empty the array ALGORITHM STEPS 1 Count Frequencies Use HashMap to count each value 2 Check Each Count If count = 1, return -1 3 Greedy Calculation ops = (count + 2) / 3 4 Sum Operations Total = sum of all ops Processing: Value Count Status 1 1 FAIL 2 2 -- 3 2 -- FINAL RESULT Processing stopped at value 1 Why -1? Value 1 appears only once. Cannot delete with 2 or 3. Output: -1 Key Insight: If any element appears exactly once (count = 1), it's impossible to delete it using either operation. For count greater than 1: Use greedy approach - maximize delete-3 operations for minimum total ops. Formula: operations = ceil(count / 3) = (count + 2) / 3 (integer division) TutorialsPoint - Minimum Number of Operations to Make Array Empty | Greedy Mathematical Approach
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