Skip to content
Decoder

Task Scheduler

Medium

Problem

A CPU has to run a list of tasks, each labelled with a capital letter. Each task takes one time unit. After running a task, the same label cannot run again for n units (a cooldown). In any unit the CPU either runs one task or sits idle. Tasks can run in any order.

Return the fewest time units needed to finish everything.

Example 1

Input
tasks = ["A","A","A","B","B","B"], n = 2
Output
8
Why
A B idle A B idle A B

Example 2

Input
tasks = ["A","A","A","B","B","B"], n = 0
Output
6
Why
no cooldown

Example 3

Input
tasks = ["A","C","A","B","D","B"], n = 1
Output
6
Why
A B A B C D

Constraints

  • 1 <= tasks.length <= 10^4
  • tasks[i] is an uppercase English letter.
  • 0 <= n <= 100

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.