Task Scheduler solution explained

Task Scheduler asks for the fewest time slots needed to run every task when copies of the same task must be at least n slots apart. The answer is max(total tasks, (f - 1) × (n + 1) + m), where f is the highest count of any task and m is how many tasks share that count. You can also reach it by simulating with a max-heap of remaining counts and a queue of tasks cooling down.

By Published 7 min read

The scheduling rules

A single processor runs tasks, each named by a letter, one per time slot. Tasks may run in any order. After a task with a given letter runs, the same letter may not run again until at least n other slots have passed. Those slots can hold other tasks or be idle. Return the smallest total number of slots that finishes every task. Note that the order is yours to choose; a different version of the question fixes the order and only asks you to count the waiting, which is a simpler hash-map exercise.

Task lists invented for this page (underscore = idle slot)
TasksnMinimum slotsOne optimal schedule
X X X Y27X Y _ X _ _ X
P P P Q Q Q R310P Q R _ P Q _ _ P Q
X X Y Y Z Z W17X Y X Y Z W Z, no idling
M M M M17M _ M _ M _ M
X X X Y04No cooldown, run them back to back
Task lists invented for this page (underscore = idle slot). Scroll sideways on a small screen.

Why it gets asked

Few candidates see the formula at once, so the question shows how you reason toward it. A typical strong path is: simulate greedily, notice that the most frequent task dictates the idle time, sketch the frames on the whiteboard, then derive the count. Interviewers also listen for a proof sketch of why running the most frequent available task first is safe, since a greedy answer without a reason is a guess.

Variations to expect

  • Return an actual schedule, not just its length. Use the simulation and record which task, or idle, fills each slot.
  • Tasks must run in the given order. Track the next allowed slot for each letter in a map and jump ahead when needed. No heap required.
  • Rearrange a string so equal letters are at least k apart, or report that it is impossible. The same heap-and-queue simulation, except idling is not allowed.
  • Several processors. The question gets much harder; talk through how the frames change rather than promising code.

Greedy simulation with a heap

At every slot, run the available task with the most copies left. Keep the remaining counts in a max-heap, and put a task that just ran into a queue together with the last slot of its cooldown. When that slot is reached, move it back into the heap. If the heap is empty during a slot, the processor idles. Because every cooling task has the same n, the queue stays in order of release time, so a plain FIFO queue is enough.

import heapq
from collections import Counter, deque


def least_intervals_by_simulation(tasks, gap):
    ready = [-c for c in Counter(tasks).values()]   # max-heap of remaining counts
    heapq.heapify(ready)
    cooling = deque()   # (last slot of its cooldown, negated remaining count)
    slot = 0
    while ready or cooling:
        slot += 1
        if ready:
            remaining = heapq.heappop(ready) + 1    # run the most common ready task once
            if remaining < 0:
                cooling.append((slot + gap, remaining))
        if cooling and cooling[0][0] == slot:
            heapq.heappush(ready, cooling.popleft()[1])
    return slot
Simulation with a max-heap of counts and a FIFO cooldown queue.

Why most-frequent-first works: the task with the most copies left is the one most likely to force idle slots at the end, so spending a slot on it now never makes things worse. The simulation runs one loop iteration per slot. With 26 possible letters each heap operation is effectively constant, so the time is proportional to the answer itself, which is at most about N × (n + 1) for N tasks.

Counting frames instead of simulating

Let f be the largest count and m the number of letters that have it. Lay out the most frequent letter f times, with n slots between neighbours. That forms f - 1 frames of length n + 1, followed by a last frame holding only the m letters that reach count f. So the schedule needs at least (f - 1) × (n + 1) + m slots. Every other task fits into the gaps of those frames. If there are more tasks than gaps, no idle slot is needed at all, and then the answer is simply the number of tasks. Take the larger of the two values.

function leastIntervals(tasks, gap) {
  const counts = new Map();
  for (const t of tasks) counts.set(t, (counts.get(t) || 0) + 1);
  let top = 0;
  for (const c of counts.values()) top = Math.max(top, c);
  let tiedAtTop = 0;
  for (const c of counts.values()) if (c === top) tiedAtTop++;
  // (top - 1) full frames of length gap + 1, then one last partial frame
  const framed = (top - 1) * (gap + 1) + tiedAtTop;
  return Math.max(tasks.length, framed);
}
Closed form from the most frequent task. O(N) time, O(1) space for a fixed alphabet.

Check it on P P P Q Q Q R with n = 3: f = 3, m = 2, so 2 × 4 + 2 = 10, which is more than the 7 tasks. On X X Y Y Z Z W with n = 1, the frames give 1 × 2 + 3 = 5, fewer than the 7 tasks, so the answer is 7 and nothing idles. An empty list returns 0 because the task count wins.

Complexity side by side

N tasks, cooldown n, alphabet of at most 26 letters
ApproachTimeSpaceWhat you get
Heap and cooldown queueO(answer), at most O(N × (n + 1))O(26)Length, and a real schedule if you record it
Frame formulaO(N)O(26)Length only
Try every orderExponentialLargeOnly useful as a test reference
N tasks, cooldown n, alphabet of at most 26 letters. Scroll sideways on a small screen.

Edge cases

  • n = 0: the answer is the number of tasks.
  • A single letter repeated, such as M M M M with n = 1: idle slots between every copy.
  • Several letters tied for the top count, which is why m appears in the formula.
  • Many distinct letters with low counts, where the task count beats the frame count.
  • An empty task list, if allowed: 0 slots.

Pitfalls

  • Forgetting m and adding only 1 for the last frame, which undercounts when letters tie for the top.
  • Returning the frame count without taking the maximum with the task count.
  • Using n slots per frame instead of n + 1. The frame includes the task itself.
  • In the simulation, releasing a cooling task one slot too early or too late. Test with n = 0 and n = 1.
  • Sorting the counts every slot instead of keeping them in a heap.

Walking the interviewer through it

Fictional example

From simulation to formula
Candidate
The order is free, so the only thing that forces idling is the cooldown on the most common task.
Candidate
If the top letter appears f times, it needs f minus one gaps of n slots between its copies. That gives f minus one frames of n plus one slots, and a final frame for the letters that tie for the top count.
Candidate
If the other tasks overflow the gaps, there's no idling and the answer is just the number of tasks. So I return the max of the two.
Interviewer
Can you prove the greedy part?
Candidate
The lower bound comes from the top letter alone, and the task count is a lower bound too. Filling the frames column by column meets whichever is larger, so the formula is tight. I can also show the heap simulation if you'd like an actual schedule.

Heaps that change over time also drive Find Median from Data Stream and Last Stone Weight. Ranking by a key and keeping the best few is the core of K Closest Points to Origin. Counting before deciding, as here, is the first step in Top K Frequent Elements. For a change of pattern, Subsets starts the backtracking problems.

How Natively can help you prepare

Task Scheduler is a good problem to rehearse aloud, because the explanation matters as much as the code. Natively can transcribe that rehearsal on Mac or Windows, and its Code hint action can suggest the frame idea when you are stuck, from a screenshot of the problem or your notes. Afterward, the saved transcript shows whether your proof sketch held together. More on the AI interview assistant.

Questions people ask

What is the formula for Task Scheduler?

max(N, (f - 1) × (n + 1) + m), where N is the number of tasks, f the highest count of any task, n the cooldown and m the number of tasks that have count f.

Why does Task Scheduler use a greedy approach?

Running the available task with the most copies left never hurts, because that task is the one most likely to force idle slots later. A max-heap of counts plus a queue of cooling tasks simulates this choice slot by slot.

What is the time complexity of Task Scheduler?

The counting formula is O(N) time with O(1) space for a fixed alphabet. The heap simulation takes one step per slot, so its time grows with the answer, at most about N × (n + 1).

When is no idle time needed in Task Scheduler?

When the other tasks are numerous enough to fill every gap left by the most frequent task. Then the answer equals the number of tasks.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP