Call a string happy if it uses only the letters a, b and c, never has the same letter three times in a row, and uses at most a copies of the letter a, at most b copies of b and at most c copies of c.
Given the three numbers a, b and c, return a happy string that is as long as possible. If several are equally long, any of them is accepted. If no happy string exists, return the empty string.
Example 1
Input: a = 2, b = 1, c = 5 Output: "ccaccabc" Why: all 8 letters fit; no letter appears 3 times running
2 more examples and the constraints
Example 2
Input: a = 0, b = 6, c = 1 Output: "bbcbb" Why: one c can split only two pairs of b
Example 3
Input: a = 1, b = 1, c = 1 Output: "abc" Why: any order of the three letters works
Constraints
- Each of a, b and c is between 0 and 100
- At least one of the three counts is above zero
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Re-sort every stepO(a + b + c)
- Max-heap of countsO(a + b + c)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Work for a = b = c = 100 | Verdict |
|---|---|---|---|
| Re-sort every step | O(a + b + c) | Passes; easy to write | |
| Max-heap of counts | O(a + b + c) | Best; the expected form |
a, b, c = copies of each letter. Both write the answer one letter at a time.
Edge cases to test
- Only one letter. a = 0, b = 0, c = 100 gives "cc": two copies, then nothing can split them.
- Too few breakers. a = 100, b = 1, c = 0 gives a length of 5, such as "aabaa".
- Plenty of every letter. a = b = c = 100 uses all 300 letters.
- Exactly enough breakers. b = 3, c = 8: four gaps of two c each fit around three b, so all 11 letters are used.
Common mistakes
- Writing two copies of the leader at once without checking what s already ends with, which can create three in a row.
- Dropping the blocked leader from the heap instead of pushing it back, which loses copies it could still use.
- Looping forever when the leader is blocked and the heap has nothing else; that is the moment to stop.
How to talk through it
- 1Clarify. Is any longest answer accepted? Must every letter be used? What if one count is 0?
- 2Say the greedy. The most plentiful letter is the hardest to fit, so spend it first, unless it would make three in a row.
- 3Handle the block. When the leader is blocked, write the runner-up once, then let the leader go again.
- 4Code it with a heap. Pop the leader, maybe pop the runner-up, push back what still has copies.
- 5Test out loud. Run 0, 0, 100 (answer "cc"), 100, 1, 0 (length 5) and 1, 1, 1.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?