Skip to content

2244. Minimum Rounds to Complete All Tasks 👍

  • 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
22
23
24
class Solution {
 public:
  int minimumRounds(vector<int>& tasks) {
    int ans = 0;
    unordered_map<int, int> count;

    for (const int task : tasks)
      ++count[task];

    // freq = 1 -> impossible
    // freq = 2 -> needs 1 round
    // freq = 3 -> needs 1 round
    // freq = 3k                           -> needs k rounds
    // freq = 3k + 1 = 3 * (k - 1) + 2 * 2 -> needs k + 1 rounds
    // freq = 3k + 2 = 3 * k       + 2 * 1 -> needs k + 1 rounds
    for (const auto& [_, freq] : count)
      if (freq == 1)
        return -1;
      else
        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
21
22
23
class Solution {
  public int minimumRounds(int[] tasks) {
    int ans = 0;
    Map<Integer, Integer> count = new HashMap<>();

    for (final int task : tasks)
      count.merge(task, 1, Integer::sum);

    // freq = 1 -> impossible
    // freq = 2 -> needs 1 round
    // freq = 3 -> needs 1 round
    // freq = 3k                           -> needs k rounds
    // freq = 3k + 1 = 3 * (k - 1) + 2 * 2 -> needs k + 1 rounds
    // freq = 3k + 2 = 3 * k       + 2 * 1 -> needs k + 1 rounds
    for (final int freq : count.values())
      if (freq == 1)
        return -1;
      else
        ans += (freq + 2) / 3;

    return ans;
  }
}
1
2
3
4
class Solution:
  def minimumRounds(self, tasks: List[int]) -> int:
    freqs = Counter(tasks).values()
    return -1 if 1 in freqs else sum((f + 2) // 3 for f in freqs)