DSA Heaps

Longest Happy String

Build the longest string with no three consecutive same characters — greedy max-heap by remaining count.

Medium
Time O((a+b+c) log 3) Space O(1)
LeetCode
7 min read
heaps greedy

Problem#

Given counts a, b, c for letters 'a', 'b', 'c', build the longest possible string with no three consecutive identical characters. Use only available letters.

Examples#

  • a = 1, b = 1, c = 7"ccaccbcc" (length 7)
  • a = 7, b = 1, c = 0"aabaa"

Constraints#

  • 0 <= a, b, c <= 100.

Hints#

Hint 1
Always pick the most-remaining letter — unless it would make a triple, in which case pick the next most.

Approach#

Max-heap of (count, char). Each step: pop top; if appending it would create a triple, pop the second instead. Push remaining back. Stop when heap is empty or the only candidate would form a triple.

Solution#

Longest Happy String
class Solution {
public:
string longestDiverseString(int a, int b, int c) {
priority_queue<pair<int,char>> pq;
if (a) pq.push({a, 'a'});
if (b) pq.push({b, 'b'});
if (c) pq.push({c, 'c'});
string out;
while (!pq.empty()) {
auto [cnt, ch] = pq.top(); pq.pop();
int n = (int)out.size();
if (n >= 2 && out[n-1] == ch && out[n-2] == ch) {
if (pq.empty()) break;
auto [cnt2, ch2] = pq.top(); pq.pop();
out += ch2;
if (--cnt2) pq.push({cnt2, ch2});
pq.push({cnt, ch});
} else {
out += ch;
if (--cnt) pq.push({cnt, ch});
}
}
return out;
}
};

Editorial#

Greedy on the most-remaining letter would create triples; the fix is “if a triple is imminent, take a different letter for one step”. The heap returns the second-largest reliably. With three letters, the heap has size ≤ 3, so each operation is effectively O(1).

Complexity#

  • Time: O(a + b + c).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.