Leetcode 621. Task Scheduler Certainly! We’ll go through the solution to the problem “621. Task Scheduler” step-by-step.
You are given a char array representing tasks that need to be executed. Each task is represented by a character and each task can be done in one unit of time. For each task, there is a cooldown period of n
units of time before another identical task can be performed. You need to determine the minimum number of units of time required to complete all tasks.
Q: Is there any constraint on the size of the tasks
array?
A: The length of tasks
will be in the range [1, 10,000].
Q: Will the cooldown period n
always be a non-negative integer?
A: Yes, the cooldown period n
is a non-negative integer.
Q: Can we assume uppercase letters only for task identifiers? A: Yes, the tasks are represented by uppercase letters (A-Z).
(maxFreq - 1) * n
to calculate the initial idle slots needed.import java.util.*;
public class TaskScheduler {
public int leastInterval(char[] tasks, int n) {
int[] taskCounts = new int[26];
// Count frequency of each task
for (char task : tasks) {
taskCounts[task - 'A']++;
}
// Sort the task frequencies in descending order
Arrays.sort(taskCounts);
int maxFreq = taskCounts[25]; // The most frequent task
// Calculate initially required idle slots
int idleSlots = (maxFreq - 1) * n;
// Reduce idle slots by placing other tasks
for (int i = 24; i >= 0 && taskCounts[i] > 0; i--) {
idleSlots -= Math.min(taskCounts[i], maxFreq - 1);
}
// If there are idle times left after placing all tasks
idleSlots = Math.max(0, idleSlots);
return tasks.length + idleSlots;
}
}
Thus, the overall time complexity is O(T).
The implemented solution efficiently determines the least time needed to schedule the tasks given the cooldown period. The use of task frequencies and idle slot computation helps ensure that the approach is optimal and adheres to the constraints provided.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?