Minimum Rounds to Complete All Tasks - Problem

You are given a 0-indexed integer array tasks, where tasks[i] represents the difficulty level of a task.

In each round, you can complete either 2 or 3 tasks of the same difficulty level.

Return the minimum rounds required to complete all the tasks, or -1 if it is not possible to complete all the tasks.

Input & Output

Example 1 — Mixed Difficulties
$ Input: tasks = [2,2,3,3,2,4,4,4,4,4]
Output: 4
💡 Note: Difficulty 2: 3 tasks → 1 round of 3. Difficulty 3: 2 tasks → 1 round of 2. Difficulty 4: 5 tasks → 1 round of 3 + 1 round of 2 = 2 rounds. Total: 1+1+2=4
Example 2 — Perfect Groups
$ Input: tasks = [2,3,3]
Output: -1
💡 Note: Difficulty 2: 1 task cannot be completed (need at least 2 tasks of same difficulty per round)
Example 3 — All Same Difficulty
$ Input: tasks = [5,5,5,5,5,5]
Output: 2
💡 Note: 6 tasks of difficulty 5 can be completed in 2 rounds of 3 tasks each

Constraints

  • 1 ≤ tasks.length ≤ 105
  • 1 ≤ tasks[i] ≤ 109

Visualization

Tap to expand
Minimum Rounds to Complete All Tasks INPUT tasks = [2,2,3,3,2,4,4,4,4,4] 2 2 3 3 2 4 4 4 4 4 Task Frequency Count: 2: 3x 3: 2x 4: 5x Colors represent difficulty levels Level 2 Level 3 Level 4 ALGORITHM STEPS 1 Count Frequencies Group tasks by difficulty 2 Check Validity If count=1, return -1 3 Greedy Calculation Use 3s first, then 2s 4 Sum All Rounds Add rounds for each level Rounds Calculation: Level 2: 3 tasks = 1 round (3) Level 3: 2 tasks = 1 round (2) Level 4: 5 tasks = 2 rounds (3+2) Total: 1 + 1 + 2 = 4 rounds FINAL RESULT 4 rounds Round Breakdown: Round 1: (3x2s) Round 2: (2x3s) Round 3: (3x4s) Round 4: (2x4s) OK - All tasks completed! Key Insight: For count n: if n%3==0, use n/3 rounds of 3. If n%3==1, use (n/3-1) rounds of 3 + 2 rounds of 2. If n%3==2, use n/3 rounds of 3 + 1 round of 2. Formula: ceil(n/3) gives minimum rounds when n >= 2. TutorialsPoint - Minimum Rounds to Complete All Tasks | Greedy Approach
Asked in
Amazon 45 Google 30 Microsoft 25
28.0K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen