1. Count tasks
Tally how often each task appears.
counts[task] = (counts[task] ?? 0) + 1Typorithm · medium
Step 1 of 8 · intro card
Greedy
Frame the schedule around the most frequent task's cooldown gaps, then fill or overflow those gaps.
Identical tasks need n cooldown slots between runs.
The most frequent task creates (max - 1) gaps of size n + 1, plus the final batch of max-frequency tasks.
If there are enough other tasks to fill every idle slot, the answer is simply the total number of tasks.
Count frequencies first.
Skeleton: (max - 1) * (n + 1) + ties.
Answer is max(skeleton, total tasks).
function leastInterval(tasks, n) {
const counts = {};
for (const task of tasks) {
counts[task] = (counts[task] ?? 0) + 1;
}
const values = Object.values(counts);
const max = Math.max(...values);
const maxCount = values.filter((c) => c === max).length;
const slots = (max - 1) * (n + 1) + maxCount;
return Math.max(slots, tasks.length);
}Connect each part of the code to the concept before you type.
Tally how often each task appears.
counts[task] = (counts[task] ?? 0) + 1The most frequent task forces the schedule's skeleton.
const max = Math.max(...values)Count how many tasks share the maximum frequency.
const maxCount = values.filter((c) => c === max).lengthFrame the schedule around the busiest task's cooldown gaps.
const slots = (max - 1) * (n + 1) + maxCountIf tasks are dense enough there are no idles, so the answer is just the count.
return Math.max(slots, tasks.length)Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.
Algorithm lab · interactive
InputTasks AAABBB · cooldown 2
Follow temporary values, local state and supporting structures at this step.
No temporary values have been saved in this frame yet.
Around this step
Small, reproducible examples · ← → step · Space play/pause · Home/End first/last state