Task Scheduler – Solution & Complexity
Solution Walkthrough
1. Understand the bottleneck
- The hard part is not ordering every task individually; it is respecting the cooldown for the most frequent letter.
- If one task appears much more often than the rest, the schedule needs gaps between its copies, and those gaps must be filled by other tasks or by idle slots.
2. Brute-force baseline
- A direct simulation keeps a max-heap of currently available task counts plus a cooldown queue storing when a task can be used again.
- That works and is a good interview stepping stone, but it still simulates every interval explicitly, including idle time.
3. Optimal counting insight
- Let
maxFreqbe the highest task frequency. Place those copies first asmaxFreq - 1full rows separated byncooldown slots. - If
maxCounttasks tie for that same highest frequency, they all occupy the last column of the frame. The minimum required frame length is(maxFreq - 1) * (n + 1) + maxCount. - The real answer is the larger of that frame length and the total number of tasks, because abundant filler tasks can eliminate all idle intervals.
4. Final solution (all languages)
The counting formula runs in linear time over the task list and constant extra space because the alphabet size is fixed.
5. Common mistakes and follow-ups
- Forgetting the tie case: if multiple tasks share the same maximum frequency, you need all of them in the last row, not just one.
- Returning the frame length directly even when many filler tasks exist; the answer can never be smaller than
tasks.length. - Follow-up: if asked to print a valid schedule, switch to the heap + cooldown simulation and emit each chosen task or an
idlemarker.