SDE & MLE Prep

1405. Longest Happy String

Problem

Build the longest possible string from at most a letters 'a', b letters 'b' and c letters 'c' such that it never contains "aaa", "bbb" or "ccc". Return any longest one (possibly "").

Example: a = 1, b = 1, c = 7 → "ccaccbcc" (or another valid string of length 8)

Greedy with a max-heap of remaining counts: append the most plentiful letter unless the last two characters are already that letter — then append the second most plentiful instead (and stop if there is none). Using the largest pile whenever allowed is what keeps the string as long as possible.

Complexity: O(a + b + c).

class Solution:
    def longestDiverseString(self, a: int, b: int, c: int) -> str:
        heap = [(-n, ch) for n, ch in ((a, "a"), (b, "b"), (c, "c")) if n]
        heapify(heap)
        out = []
        while heap:
            n1, c1 = heappop(heap)
            if len(out) >= 2 and out[-1] == out[-2] == c1:
                if not heap:
                    break
                n2, c2 = heappop(heap)
                out.append(c2)
                if n2 + 1:
                    heappush(heap, (n2 + 1, c2))
                heappush(heap, (n1, c1))
            else:
                out.append(c1)
                if n1 + 1:
                    heappush(heap, (n1 + 1, c1))
        return "".join(out)