Minimum Rounds to Complete All Tasks
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.
tasks = [2, 2, 3, 3, 2, 4, 4, 4, 4, 4]4def 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;
}
Explanation
Tasks of different difficulties never mix in a round, so the problem splits into independent buckets — one per difficulty. We first count how many tasks each difficulty has using a frequency map.
Within one bucket of c tasks, every round clears 2 or 3 tasks. The fewest rounds is reached by using as many 3-clears as possible, which is exactly ⌈c / 3⌉ rounds. The code writes this as (c + 2) // 3.
There is one impossible case: a bucket with exactly 1 task. You cannot do a round of just one, so we immediately return -1.
Example: tasks = [2,2,3,3,2,4,4,4,4,4]. Difficulty 2 has 3 tasks → 1 round, difficulty 3 has 2 → 1 round, difficulty 4 has 5 → ⌈5/3⌉ = 2 rounds. Total = 4.
Summing ⌈c/3⌉ over all buckets (after the single-task check) gives the minimum total rounds.