Problem Description
Given an integer array tasks where tasks[i] represents the difficulty level of a task, determine the minimum number of rounds required to complete all tasks. In each round, you can complete either 2 or 3 tasks of the same difficulty level. Return -1 if it is not possible to complete all tasks under these conditions.
Key Insights
- Count the frequency of each task difficulty.
- For each difficulty level, if the frequency is 1 then it is impossible to complete those tasks.
- For frequencies greater than 1, optimally use rounds of 3 tasks wherever possible to minimize the number of rounds.
- Handle remainders carefully:
- If frequency modulo 3 is 0, use frequency/3 rounds.
- If frequency modulo 3 is 1, reduce one group of 3 to combine with the remaining 1 (i.e., (frequency - 4)/3 + 2 rounds).
- If frequency modulo 3 is 2, the answer is frequency//3 + 1 rounds.
Space and Time Complexity
Time Complexity: O(n) where n is the number of tasks, since we iterate over the list once to count frequencies and then over the distinct difficulties. Space Complexity: O(k) where k is the number of unique difficulties (k <= n).
Solution
The approach uses a hash table (or dictionary) to count the frequency of each difficulty level in the tasks array. For each unique difficulty, apply the following logic:
- If the frequency is 1, return -1 as it is impossible to group a single task into rounds of 2 or 3.
- Otherwise, calculate the minimum number of rounds required using greedy grouping:
- If frequency % 3 == 0, the number of rounds is frequency / 3.
- If frequency % 3 == 1, adjust by using one less group of 3 (i.e. frequency - 4) and add two rounds for the remaining 4 tasks.
- If frequency % 3 == 2, add one extra round to the frequency // 3. This method guarantees the minimum rounds are used to complete the tasks.