Skip to the code
cf.
+25 XP

#400 Spread Out Repeated Toasts

medium

A toast queue has messages of different types, written as one lowercase letter each in the string types. Two toasts of the same type in a row look like a glitch, so you reorder them.

Write spreadToasts(types) that builds the new order one toast at a time with this rule: at each step, pick the type with the most toasts left, among the types that are different from the previous toast; if several types tie, pick the alphabetically smallest. If at some step no type can be picked, return "". Otherwise return the full new string.

Example 1

Input: types = "aab"
Output: "aba"

a has the most left, then only b can follow a, then a.

Example 2

Input: types = "aaab"
Output: ""

After a, b, a, only an a is left, and it can't follow an a.

Constraints

  • 1 <= types.length <= 500
  • Only lowercase letters.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).