Skip to main content
Back to problems
#2870
Medium Algorithms

Minimum number of operations to make array empty

Array Hash Table Greedy Counting
62.1% acceptance
Feb 25, 2026
1441
70
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.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn min_operations(nums: Vec<i32>) -> i32 {
    use std::collections::HashMap;
    let mut freq: HashMap<i32, i32> = HashMap::new();
    for &v in &nums { *freq.entry(v).or_insert(0) += 1; }
    let mut ans = 0;
    for (_, &cnt) in freq.iter() {
      if cnt == 1 { return -1; }
      // Minimum ops for cnt items: ceil(cnt/3)
      ans += (cnt + 2) / 3;
    }
    ans
  }
}