Minimum Number of Operations to Make Array Empty

You are given an array `nums` of positive integers. In one operation you may delete two elements with equal values, or three elements with equal values. Return the minimum number of operations needed to make the array empty, or `-1` if it cannot be done.

30:00

Minimum Number of Operations to Make Array Empty
medium
Free written solution
Topics
Companies

You are given an array nums of positive integers. In one operation you may delete two elements with equal values, or three elements with equal values. Return the minimum number of operations needed to make the array empty, or -1 if it cannot be done.

Example 1:
Input: {"nums":[2,3,3,2,2,4,2,3,4]}
Output: 4
Constraints:
  • 2≤nums.length≤1052 \leq \text{nums.length} \leq 10^5

  • 1≤nums[i]≤1061 \leq \text{nums}[i] \leq 10^6

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"nums":[2,3,3,2,2,4,2,3,4]}

nums

2
3
3
2
2
4
2
3
4

each value cut into triples, then pairs

ops 0

2 x0

not seen yet

3 x0

not seen yet

4 x0

not seen yet

[•••] remove 3

[••] remove 2

9 numbers. An operation only removes equal values, so each distinct value can be handled on its own. Start by counting them.

Variables
VariableValue
ops0
DepthFunction Call
Stack empty
0/16