Longest Happy String Problem
Description
LeetCode Problem 1405.
A string s is called happy if it satisfies the following conditions:
sonly contains the letters'a','b', and'c'.sdoes not contain any of"aaa","bbb", or"ccc"as a substring.scontains at mostaoccurrences of the letter'a'.scontains at mostboccurrences of the letter'b'.scontains at mostcoccurrences of the letter'c'.
Given three integers a, b, and c, return the longest possible happy string. If there are multiple longest happy strings, return any of them. If there is no such string, return the empty string "".
A substring is a contiguous sequence of characters within a string.
Example 1:
Input: a = 1, b = 1, c = 7
Output: "ccaccbcc"
Explanation: "ccbccacc" would also be a correct answer.
Example 2:
Input: a = 7, b = 1, c = 0
Output: "aabaa"
Explanation: It is the only correct answer in this case.
Constraints:
0 <= a, b, c <= 100a + b + c > 0
Solution
Approach: Greedy, Most Remaining Letter First
Build the string one letter at a time. At each step, try the letters in order of how many copies are left, most first, and append the first one that is still available and would not make three equal letters in a row (that is, the string does not already end with two copies of it). If no letter can be appended, stop.
Usually this appends the most plentiful letter. When the string already ends with two copies of it, we append the next most plentiful letter instead, which breaks the run so that the most plentiful letter can be used again on the next step.
Why the greedy is optimal: the only thing that can cut the string short is one letter having too many copies to separate. Spending the most plentiful letter whenever possible keeps the counts as balanced as they can be, so we never use up the separator letters early. With the counts sorted as x >= y >= z, the longest happy string has length min(x, 2 * (y + z + 1)) + y + z: the y + z other letters split the big letter into at most y + z + 1 runs of at most 2, and the greedy reaches this bound.
In Example 2 (a = 7, b = 1), the greedy writes aa, then b because a third a is not allowed, then aa, and stops because the string ends in aa and no b or c is left: "aabaa". Several answers can be correct (Example 1), and any longest happy string is accepted.
Complexity: O(a + b + c) time, since each step appends one letter after sorting three counts, and O(1) extra space apart from the answer.
class Solution:
def longestDiverseString(self, a: int, b: int, c: int) -> str:
count = [a, b, c]
ans = []
while True:
placed = False
for i in sorted(range(3), key=lambda i: -count[i]): # most remaining first
letter = "abc"[i]
# Skip a letter that is used up or would make three in a row.
if count[i] > 0 and ans[-2:] != [letter, letter]:
ans.append(letter)
count[i] -= 1
placed = True
break
if not placed:
return "".join(ans)