Your free access ends in 7 days — and you haven’t tried it yet. Watch one algorithm run, start to finish. It takes about two minutes.

Try one problem
0
Problem

Task Scheduler

LeetCode #621Medium
Most-frequent-first · max-heap vs. the frame formula

Given task labels and a cooldown n, the same task must run at least n intervals apart. Return the minimum number of intervals (including idles) needed to finish every task.

Asked atAmazonMetaGoogle
step 1 / 19
A
A
A
B
B
B
[0][1][2][3][4][5]
schedule
Greedy · most-frequent-first (max-heap)
1count tasks; heap = max-heap by remaining count
2time = 0
3while tasks remain:
4 run up to n+1 distinct tasks, highest count first
5 (decrement; re-add to heap if count > 0)
6 if a slot has no available task → idle
7 advance one cooldown frame
8return time
state
  • n (cooldown)2
  • A3
  • B3

line 1Schedule all 6 tasks so equal labels stay ≥ n = 2 intervals apart, with the FEWEST intervals (idles count). The bottleneck is the MOST FREQUENT task — give it priority and pack the gaps around it.