Task Scheduler

MediumGreedygreedy / counting

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You are given a list of CPU tasks, where each task is labeled by an uppercase letter ('A' through 'Z'). Tasks with the same label are identical units of work, and the CPU can complete one task per time unit. There is a catch: two tasks with the **same** label must be separated by a cooldown period. Specifically, after the CPU runs a task, at least n time units must pass before that same label can run again. During any time unit the CPU may either run an available task or stay **idle**. Given the array tasks and the integer n, return the **minimum number of time units** the CPU needs to finish every task. Tasks may be executed in any order.

Examples

Input: tasks = ["A","A","A","B","B","B"], n = 2
Output: 8
One valid schedule is A -> B -> idle -> A -> B -> idle -> A -> B. Each pair of identical tasks is separated by at least 2 time units, giving 8 total units.
Input: tasks = ["A","B","C","D","E","F"], n = 0
Output: 6
Every task is distinct (or n is 0), so there is no waiting. The CPU runs all 6 tasks back to back.
Input: tasks = ["A","A","A","B","B","B"], n = 0
Output: 6
With no cooldown required, all 6 tasks run consecutively with no idle time.

Constraints

  • `1 <= tasks.length <= 10^4`
  • `tasks[i]` is an uppercase English letter (`'A'` to `'Z'`)
  • `0 <= n <= 100`

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.