LeetCode 2365: Task Scheduler II Solution
Master LeetCode problem 2365 (Task Scheduler II), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
2365. Task Scheduler II
Problem Explanation
Explanation
To solve this problem, we can simulate the task completion process day by day. We keep track of the last day each task type was completed and use that information to decide whether we can perform the task on the current day or if a break is needed. We maintain a priority queue to store the tasks based on the next available day they can be completed.
- Create a map to store the last completion day of each task type.
- Create a priority queue to store tasks based on the next available day they can be completed.
- Iterate over the tasks and update the last completion day in the map.
- For each task, check if it can be completed on the current day based on the space constraint. If not, add it to the priority queue.
- If the priority queue is not empty, simulate taking a break until the next task can be performed and update the current day accordingly.
- Repeat the process until all tasks are completed.
Time Complexity: O(n log n) where n is the number of tasks Space Complexity: O(n)
Solution Code
class Solution {
public int taskScheduler(int[] tasks, int space) {
Map<Integer, Integer> lastCompletion = new HashMap<>();
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[1] - b[1]);
int day = 0;
for (int i = 0; i < tasks.length; i++) {
int task = tasks[i];
if (lastCompletion.containsKey(task) && day - lastCompletion.get(task) <= space) {
pq.offer(new int[]{task, lastCompletion.get(task) + space + 1});
} else {
lastCompletion.put(task, day);
}
day++;
}
while (!pq.isEmpty()) {
int[] nextTask = pq.poll();
day = Math.max(day, nextTask[1]);
lastCompletion.put(nextTask[0], day);
day++;
}
return day;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2365 (Task Scheduler II)?
This page provides optimized solutions for LeetCode problem 2365 (Task Scheduler II) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2365 (Task Scheduler II)?
The time complexity for LeetCode 2365 (Task Scheduler II) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2365 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2365 in Java, C++, or Python.