medium Minimum Number of Operations to Make Array Empty
Problem Statement
You are given an array nums consisting of positive integers.
You can perform below two operations on the array multiple times:
- Select
two elementswithequal valuesanddeletethem from the array. - Select
three elementswithequal valuesanddeletethem from the array.
Return the minimum number of operations required to make the array empty, or -1 if it is not possible.
Examples
Example 1:
- Input: nums =
[1, 3, 2, 1, 2, 2, 3] - Expected Output:
3 - Justification: We can perform the following operations:
- Remove the two
1s (one operation). - Remove the three
2s (second operation). - Remove the two
3s (third operation). Thus, the array can be emptied in 3 operations.
- Remove the two
Example 2:
- Input: nums =
[4, 4, 2, 5, 3, 2, 5, 3] - Expected Output:
4 - Justification: We can perform operations such as removing pairs of
4,2,5, and3in successive steps, each taking one step. This results in the array being emptied in 4 operations.
Example 3:
- Input: nums =
[7, 8, 7] - Expected Output:
-1 - Justification: It is not possible to make the array empty as we can't remove 8 by performing any of 2 operations.
Try it yourself
Try solving this question here:
✅ Solution Minimum Number of Operations to Make Array Empty
Problem Statement
You are given an array nums consisting of positive integers.
You can perform below two operations on the array multiple times:
- Select
two elementswithequal valuesanddeletethem from the array. - Select
three elementswithequal valuesanddeletethem from the array.
Return the minimum number of operations required to make the array empty, or -1 if it is not possible.
Examples
Example 1:
- Input: nums =
[1, 3, 2, 1, 2, 2, 3] - Expected Output:
3 - Justification: We can perform the following operations:
- Remove the two
1s (one operation). - Remove the three
2s (second operation). - Remove the two
3s (third operation). Thus, the array can be emptied in 3 operations.
- Remove the two
Example 2:
- Input: nums =
[4, 4, 2, 5, 3, 2, 5, 3] - Expected Output:
4 - Justification: We can perform operations such as removing pairs of
4,2,5, and3in successive steps, each taking one step. This results in the array being emptied in 4 operations.
Example 3:
- Input: nums =
[7, 8, 7] - Expected Output:
-1 - Justification: It is not possible to make the array empty as we can't remove 8 by performing any of 2 operations.
Solution
To solve this problem, we start by counting the occurrences of each integer in the given array, which is crucial for determining the feasible operations we can perform. This counting process involves traversing the array once and maintaining a frequency count for each distinct element in a hash map or an object. The key insight here is that by knowing the exact count of each number, we can decide on the optimal combination of operations (removing pairs or triplets of numbers) to minimize the total number of operations required to empty the array. The decision to remove pairs or triplets is guided by the aim to perform the least number of operations, which directly depends on how these counts are distributed among the numbers in the array.
Once the counts are established, we iterates over these counts to calculate the total operations needed. For each element's count, if there is only one occurrence, the array cannot be made empty according to the rules, and we return -1. Otherwise, we employ a simple mathematical operation: divide each count by 3 and round up the result to determine the minimum number of operations required for each number. This approach ensures that we efficiently utilize the allowed operations to minimize the total count, leveraging the fact that removing three elements in one operation or two in another is the most efficient way to reduce the array size.
Step-by-Step Algorithm
- Initialize a hash map or an object to store the count of each unique element in the input array.
- Iterate over the input array, updating the count for each element in the hash map.
- Initialize a variable to keep track of the total number of operations required.
- Iterate over the counts stored in the hash map:
- If any count is exactly 1, return
-1immediately, as it's impossible to remove this element through the given operations. - For each count, add to the total number of operations the result of dividing the count by 3 and rounding up. This calculation aligns with the allowed operations (removing either two or three elements of the same value at a time).
- If any count is exactly 1, return
- After processing all counts, return the total number of operations as the result.
Algorithm Walkthrough
Let's consider the Input [4, 4, 2, 5, 3, 2, 5, 3]
- Count occurrences: The counts are
{1: 2, 3: 2, 2: 3}. - Calculate operations for
1: Count is2. Removing both1s in one operation, total operations now are1. - Calculate operations for
3: Count is2. Removing both3s in one operation, total operations increase to2. - Calculate operations for
2: Count is3. Removing all three2s in one operation, total operations become3. - No counts of
1left: It's possible to make the array empty with the given operations. - Return total operations: The final answer is
3, as calculated, meaning the array can be emptied in 3 operations.
Code
import java.util.HashMap;
public class Solution {
public int minOperations(int[] nums) {
var elementCount = new HashMap<Integer, Integer>(); // Changed from 'counter' to 'elementCount' for clarity
for (int num : nums) {
elementCount.put(num, elementCount.getOrDefault(num, 0) + 1);
}
int totalOperations = 0; // Changed from 'ans' to 'totalOperations' for clarity
for (int count : elementCount.values()) {
if (count == 1) {
return -1; // It's not possible to make the array empty
}
totalOperations += Math.ceil((double) count / 3);
}
return totalOperations;
}
public static void main(String[] args) {
Solution solution = new Solution();
System.out.println(
solution.minOperations(new int[] { 1, 3, 2, 1, 2, 2, 3 })
); // Expected: 3
System.out.println(
solution.minOperations(new int[] { 4, 4, 2, 5, 3, 2, 5, 3 })
); // Expected: 4
System.out.println(solution.minOperations(new int[] { 7, 8, 7 })); // Expected: -1
}
}
Complexity Analysis
Time Complexity
: This is because each element in the array numsis processed exactly once to count occurrences. Thenhere represents the total number of elements in the input array.- The iteration over the hash map (or dictionary) to calculate the total operations has a complexity of
, where uis the number of unique elements in the array. Sinceu <= n, this does not exceedin terms of the overall impact on time complexity.
Space Complexity
: The space complexity is determined by the size of the hash map (or dictionary) used to count the occurrences of each unique element. In the worst case, where all elements are unique, this would be O(n), but typically u <= n, making the space complexity.
🤖 Don't fully get this? Learn it with Claude
Stuck on Minimum Number of Operations to Make Array Empty? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.
Progressively stronger hints — you still solve it.
I'm working on the problem **Minimum Number of Operations to Make Array Empty** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
See the technique, not just code.
Explain the optimal approach to **Minimum Number of Operations to Make Array Empty** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Catch bugs, edge cases, sub-optimality.
I'll paste my solution to **Minimum Number of Operations to Make Array Empty**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Lock in recognition with look-alikes.
Give me 2 problems that use the SAME underlying pattern as **Minimum Number of Operations to Make Array Empty**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.