Skip to content

2365. Task Scheduler II 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
 public:
  long long taskSchedulerII(vector<int>& tasks, int space) {
    unordered_map<int, long> taskToNextAvailable;
    long ans = 0;

    for (const int task : tasks) {
      ans = max(ans + 1, taskToNextAvailable[task]);
      taskToNextAvailable[task] = ans + space + 1;
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution {
  public long taskSchedulerII(int[] tasks, int space) {
    Map<Integer, Long> taskToNextAvailable = new HashMap<>();
    long ans = 0;

    for (final int task : tasks) {
      ans = Math.max(ans + 1, taskToNextAvailable.getOrDefault(task, 0L));
      taskToNextAvailable.put(task, ans + space + 1);
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution:
  def taskSchedulerII(self, tasks: list[int], space: int) -> int:
    taskToNextAvailable = collections.defaultdict(int)
    ans = 0

    for task in tasks:
      ans = max(ans + 1, taskToNextAvailable[task])
      taskToNextAvailable[task] = ans + space + 1

    return ans