Gym Sets With Rest

HardgreedyAlso known as Task Scheduler

Your workout card lists sets, each tagged with a muscle group: L for legs, C for chest, B for back, and so on. Each time slot holds one set or a rest, and you may do the sets in any order. The coach's rule is that after a set for a group, at least rest other slots (other sets or rests) must pass before that group again. Finish 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. The three L sets force this length on their own, because the first and last L must be at least 2 × 3 = 6 slots apart, which makes 7 slots in total. C fills a gap but cannot shorten the schedule.

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

The order L C L C A B needs no rest, because every L and C is followed by a different group. There are 6 sets, so 6 is the minimum.

Constraints

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

Trying every allowed order slot by slot grows exponentially, so even 30 sets is out of reach. Greedily picking the allowed group with the most sets left is correct, but it builds the whole schedule even though 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