Minimum Rounds to Complete All Tasks

medium array hash map greedy counting

Problem

Given an array tasks where tasks[i] is the difficulty of the i-th task, each round you may complete 2 or 3 tasks of the same difficulty. Return the minimum rounds to complete all tasks, or -1 if impossible.

Inputtasks = [2, 2, 3, 3, 2, 4, 4, 4, 4, 4]
Output4
difficulty 2 (x3) → 1 round; difficulty 3 (x2) → 1 round; difficulty 4 (x5) → 2 rounds.

def minimum_rounds(tasks):
    from collections import Counter
    cnt = Counter(tasks)
    rounds = 0
    for c in cnt.values():
        if c == 1: return -1
        rounds += (c + 2) // 3
    return rounds
function minimumRounds(tasks) {
  const cnt = new Map();
  for (const t of tasks) cnt.set(t, (cnt.get(t) || 0) + 1);
  let rounds = 0;
  for (const c of cnt.values()) {
    if (c === 1) return -1;
    rounds += Math.ceil(c / 3);
  }
  return rounds;
}
class Solution {
    public int minimumRounds(int[] tasks) {
        Map<Integer, Integer> cnt = new HashMap<>();
        for (int t : tasks) cnt.merge(t, 1, Integer::sum);
        int rounds = 0;
        for (int c : cnt.values()) {
            if (c == 1) return -1;
            rounds += (c + 2) / 3;
        }
        return rounds;
    }
}
int minimumRounds(vector<int>& tasks) {
    unordered_map<int, int> cnt;
    for (int t : tasks) cnt[t]++;
    int rounds = 0;
    for (auto& [k, c] : cnt) {
        if (c == 1) return -1;
        rounds += (c + 2) / 3;
    }
    return rounds;
}
Time: O(n) Space: O(n)