Skip to content

2870. Minimum Number of Operations to Make Array Empty 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
 public:
  int minOperations(vector<int>& nums) {
    int ans = 0;
    unordered_map<int, int> count;

    for (const int num : nums)
      ++count[num];

    for (const auto& [_, freq] : count) {
      // If freq == 3k, need k operations.
      // If freq == 3k + 1 = 3*(k - 1) + 2*2, need k + 1 operations.
      // If freq == 3k + 2, need k + 1 operations.
      if (freq == 1)
        return -1;
      ans += (freq + 2) / 3;
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
  public int minOperations(int[] nums) {
    int ans = 0;
    Map<Integer, Integer> count = new HashMap<>();

    for (final int num : nums)
      count.merge(num, 1, Integer::sum);

    for (final int freq : count.values()) {
      // If freq == 3k, need k operations.
      // If freq == 3k + 1 = 3*(k - 1) + 2*2, need k + 1 operations.
      // If freq == 3k + 2, need k + 1 operations.
      if (freq == 1)
        return -1;
      ans += (freq + 2) / 3;
    }

    return ans;
  }
}
1
2
3
4
5
6
class Solution:
  def minOperations(self, nums: list[int]) -> int:
    count = collections.Counter(nums)
    if 1 in count.values():
      return -1
    return sum((freq + 2) // 3 for freq in count.values())