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:
Return the minimum number of operations required to make the array empty, or -1
if it is not possible.
For example:
nums = [2,3,3,2,2,4,2,3,4]
In this case, the function should return 4, because we can apply the following operations to make the array empty:
nums = [3,3,2,4,2,3,4]
.nums = [3,3,4,3,4]
.nums = [4,4]
.nums = []
.It can be shown that we cannot make the array empty in less than 4 operations.
Here is another example:
nums = [2,1,2,2,3,3]
In this case, the function should return -1, because it is impossible to empty the array.
Write a function that takes an array of integers as input and returns the minimum number of operations to empty the array, or -1 if it is not possible.
What is the time and space complexity of your solution?
You are given a 0-indexed array nums
consisting of positive integers. You can perform the following operations any number of times:
Return the minimum number of operations required to make the array empty, or -1
if it is not possible.
A naive approach would be to try all possible combinations of deleting pairs and triplets of equal elements. This involves recursion and backtracking. However, this approach is highly inefficient due to the overlapping subproblems and exponential time complexity.
A more efficient approach involves counting the occurrences of each number in the array. Then, for each number, we determine the minimum number of operations needed to reduce its count to zero using only operations that remove two or three elements at a time.
Specifically, for a count n
:
n
is 1, it's impossible to empty the array (return -1).n
is even, we can use n / 2
operations of type 1 (pairs).n
is divisible by 3, we can use n / 3
operations of type 2 (triplets).We can derive the operations by looking at the following cases
from collections import Counter
import math
def min_operations(nums):
counts = Counter(nums)
operations = 0
for count in counts.values():
if count == 1:
return -1
operations += math.ceil(count / 3)
return operations
Counter
object will store n key-value pairs.2 <= nums.length <= 10^5
, so we don't need to worry about empty arrays.nums = [2, 3, 3, 2, 2, 4, 2, 3, 4]
result = min_operations(nums)
print(result) # Output: 4
For 2: 4 can be resolved using two operations of type 1 (2 pairs). For 3: 3 can be resolved using one operation of type 2 (1 triplet). For 4: 2 can be resolved using one operation of type 1 (1 pair).
Total operations: 2 + 1 + 1 = 4.