Typorithm · medium

Task Scheduler

▷ Interactive algorithm labtask-schedulergreedyfrequencyidle-slotsgreedy-choice
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Task Scheduler

0%

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.

Preparing algorithm lab…
01

Count frequencies first.

02

Skeleton: (max - 1) * (n + 1) + ties.

03

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);
}

Read the implementation

Connect each part of the code to the concept before you type.

1. Count tasks

Tally how often each task appears.

counts[task] = (counts[task] ?? 0) + 1

2. Busiest task

The most frequent task forces the schedule's skeleton.

const max = Math.max(...values)

3. Ties

Count how many tasks share the maximum frequency.

const maxCount = values.filter((c) => c === max).length

4. Slot formula

Frame the schedule around the busiest task's cooldown gaps.

const slots = (max - 1) * (n + 1) + maxCount

5. Lower bound

If tasks are dense enough there are no idles, so the answer is just the count.

return Math.max(slots, tasks.length)

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Task Scheduler: Visual Walkthrough & Practice · Typorithm | ApplyDjinn