#621

Task Scheduler

Medium
ArrayHash TableGreedySortingHeap (Priority Queue)CountingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution uses a greedy approach to maximize the usage of the CPU while respecting the cooling interval. We prioritize tasks based on their frequency and fill the idle slots as needed.

⚙️

Algorithm

4 steps
  1. 1Step 1: Count the frequency of each task using a HashMap.
  2. 2Step 2: Identify the maximum frequency and how many tasks have that frequency.
  3. 3Step 3: Calculate the total intervals required using the formula: (max_freq - 1) * (n + 1) + tasks_with_max_freq.
  4. 4Step 4: Return the maximum of total intervals and the length of the tasks array.
solution.py8 lines
1from collections import Counter
2
3def leastInterval(tasks, n):
4    task_counts = Counter(tasks)
5    max_freq = max(task_counts.values())
6    max_count = sum(1 for count in task_counts.values() if count == max_freq)
7    total_intervals = (max_freq - 1) * (n + 1) + max_count
8    return max(total_intervals, len(tasks))

Complexity note: The time complexity is O(n) due to counting the tasks and calculating the intervals, which is efficient for this problem.

  • 1Understanding task frequency is crucial to optimizing the scheduling.
  • 2The cooling interval n directly affects how tasks can be arranged.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.