1744. Cooldown Timeline

Medium3.5 points estimatedGreedyHeapStringCounting

A kitchen robot prepares dishes, each coded by an uppercase letter in tasks. It handles one dish per time slot, and after preparing a dish of some type it must wait: two dishes of the same letter need at least n other slots (dishes or idle slots) between them. The robot may stay idle in a slot.

Return a shortest valid timeline as a string, one character per slot: the dish letter, or '-' for an idle slot. Every dish must appear exactly once per occurrence in tasks. Several shortest timelines may exist and any valid one is accepted. The shortest length equals max(len(tasks), (maxFreq - 1) * (n + 1) + number of letters with maxFreq). Aim for O(L) time, where L is the output length, by always scheduling the most frequent letter that is off cooldown.

Example 1

Input:
tasks = "AAABBB", n = 2
Output:
"AB-AB-AB"
Explanation:

Each A and each B needs two slots before the same letter returns, so one idle slot is needed after each pair, giving length 8; for example AB-AB-AB.

Example 2

Input:
tasks = "AAAB", n = 0
Output:
"AAAB"
Explanation:

With n = 0 no waiting is needed, so the four dishes take four slots in any order.

Example 3

Input:
tasks = "AABC", n = 1
Output:
"ABAC"
Explanation:

The two A dishes need one slot between them, which a B or C can fill, so no idle slot is needed and the length is 4.

Constraints

1 ≤ tasks.length ≤ 100
0 ≤ n ≤ 20
tasks consists of uppercase English letters
the returned timeline has length at most 2100

How this problem is judged

Answers
Any valid answer is accepted. A checker tests yours against the problem's rules.
Time per case
Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms

Expected complexity

Time
O(L)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…