Gym Sets With Rest

HardgreedyAlso known as Task Scheduler

Your coach hands you a workout card listing sets to do, each tagged with the muscle group it works: L for legs, C for chest, B for back, and so on. You do one thing per slot of time: either one set, or rest. You may do the sets in any order you like.

The coach has one rule: after a set for some muscle group, at least rest other slots must pass before you work that same group again. Those slots can be sets for other groups or plain rest. You want to finish the card in as few slots as possible.

Your task

Write fewestSlots(sets, rest). sets is a string of uppercase letters, one per set; equal letters are the same muscle group. Between two sets of the same group there must be at least rest other slots. Return the smallest total number of slots, counting rest slots, needed to do every set.

An empty card takes 0 slots. With rest = 0 there is no restriction.

fewestSlots(sets: string, rest: int) → int

Examples

Example 1
Input
sets = "LLLC"
rest = 2
Output
7
Why

One best order is L C _ L _ _ L, where _ is a rest slot. Every pair of L sets has 2 slots between them. The three L sets alone force this length: the first and last L are at least 2 × 3 = 6 slots apart, so at least 7 slots in total. The one C set fills a gap but cannot shorten it.

Example 2
Input
sets = "LLCCAB"
rest = 1
Output
6
Why

L C L C A B works with no rest at all: each L and each C has another group's set right after it. You can never beat 6, since there are 6 sets.

Constraints

  • 0 ≤ sets.length ≤ 10,000
  • sets contains only the letters A to Z
  • 0 ≤ rest ≤ 100
Start with brute force

Simulate slot by slot, and at each slot try every group that is allowed right now, plus resting, exploring all orders to find the shortest. The number of orders grows exponentially with the number of sets, so even 30 sets is out of reach.

A cheaper simulation picks, at each slot, the allowed group with the most sets left. That is correct, but it builds the whole schedule slot by slot, which is far more work than needed: the answer depends only on how many sets the busiest groups have.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code