1749. Capped Letter Runs
A sign painter has counts[i] tiles showing the lowercase letter 'a' + i, for the 26 letters. They want to line up as many tiles as possible so that no letter appears more than limit times in a row. A letter may be used at most counts[i] times in total, and some tiles can stay unused.
Return one longest valid arrangement as a string (it is never empty, because at least one tile exists). Many longest arrangements can exist and any valid one is accepted. A greedy works in O(L) time, where L is the output length, with O(1) extra space for the 26 letters: at each step place the letter with the most tiles left, preferring the earlier letter on a tie, unless it would exceed the run cap, in which case use the next best letter; stop when nothing can be placed.
Example 1
- Input:
- counts = [5,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]limit = 2
- Output:
- "aabaa"
- Explanation:
The single b can split the a tiles into at most two runs of two, so five tiles is the longest valid line: aabaa.
Example 2
- Input:
- counts = [2,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]limit = 1
- Output:
- "abcabc"
- Explanation:
With a cap of one, equal letters may not touch, and abcabc uses all six tiles.
Example 3
- Input:
- counts = [3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]limit = 1
- Output:
- "a"
- Explanation:
Only the letter a exists and it may not repeat, so the longest line is a single tile.
Constraints
counts.length == 26
0 ≤ counts[i]
1 ≤ sum(counts) ≤ 2000
1 ≤ limit ≤ 100
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)