Task Scheduler II - Problem

You are given a 0-indexed array of positive integers tasks, representing tasks that need to be completed in order, where tasks[i] represents the type of the i-th task.

You are also given a positive integer space, which represents the minimum number of days that must pass after the completion of a task before another task of the same type can be performed.

Each day, until all tasks have been completed, you must either:

  • Complete the next task from tasks, or
  • Take a break.

Return the minimum number of days needed to complete all tasks.

Input & Output

Example 1 — Basic Case
$ Input: tasks = [1,2,1,2], space = 3
Output: 6
💡 Note: Day 1: Task 1, Day 2: Task 2, Day 5: Task 1 (wait 3 days), Day 6: Task 2 (wait 3 days)
Example 2 — No Waiting Needed
$ Input: tasks = [5,8,8,5], space = 2
Output: 7
💡 Note: Day 1: Task 5, Day 2: Task 8, Day 5: Task 8 (wait 2 days), Day 7: Task 5 (wait 2 days)
Example 3 — Single Task Type
$ Input: tasks = [1,1,1], space = 2
Output: 7
💡 Note: Day 1: Task 1, Day 4: Task 1 (wait 2 days), Day 7: Task 1 (wait 2 days)

Constraints

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

Visualization

Tap to expand
Task Scheduler II - Hash Map Tracking INPUT tasks array: 1 idx 0 2 idx 1 1 idx 2 2 idx 3 space = 3 min days between same type Same task type needs at least 3 days gap T1 ... 3 days ... T1 Tasks must be done in order ALGORITHM STEPS 1 Initialize HashMap for last day of task day = 0, lastDay = {} 2 Process Each Task Check if task was done before 3 Wait if Needed day = max(day, lastDay[t]+space+1) 4 Update and Continue lastDay[task] = day++ Execution Trace Task 1: day=0, last={1:0} Task 2: day=1, last={1:0,2:1} Task 1: wait! day=4 (0+3+1) Task 2: wait! day=5 (1+3+1) Final: day = 6 FINAL RESULT Day-by-Day Timeline: 1 Day 0 2 Day 1 - Day 2 - Day 3 1 Day 4 2 Day 5 Task type 1 Task type 2 Break day 3 days gap (space=3) 3 days gap (space=3) Output: 6 OK - 6 days minimum Key Insight: Use a HashMap to track the last day each task type was completed. For each new task, calculate the earliest possible day: max(current_day, last_occurrence + space + 1). This greedy approach ensures minimum waiting while respecting the space constraint. Time: O(n), Space: O(n) TutorialsPoint - Task Scheduler II | Hash Map Tracking Approach
Asked in
Facebook 15 Google 12 Amazon 8
18.8K 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