Longest Happy String
Longest Happy String is a medium heaps problem solved with the advanced pattern.
The best approach, optimal (max-heap greedy), runs in O(a + b + c) time and O(1) space.
Below are 2 approaches in Java, Python, C++ and JavaScript, from greedy with a three-letter scan up.
Problem
You are given three non-negative integers a, b and c. A string is called happy when it uses only the letters 'a', 'b' and 'c', never contains three equal letters in a row (so none of "aaa", "bbb" or "ccc" appears in it), and uses the letter 'a' at most a times, 'b' at most b times and 'c' at most c times.
Return the longest happy string you can build. If several happy strings share the longest length, return any one of them. If no non-empty happy string exists, return the empty string "".
Examples
Example 1
- Input
a = 1, b = 1, c = 5- Output
"ccaccbc"- Why
- All seven letters fit. The a and the b split the five c's into runs of two, two and one. Other strings of the same length, such as "ccbccac", are also accepted.
Example 2
- Input
a = 7, b = 1, c = 0- Output
"aabaa"- Why
- The single b can separate only two runs of a, and each run holds at most two a's. So only four a's can be used, and the longest happy string has length 5.
Example 3
- Input
a = 0, b = 0, c = 2- Output
"cc"- Why
- Two equal letters in a row are allowed; only three in a row are not.
Constraints
0 <= a, b, c <= 100a + b + c > 0
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (3 examples, or your own). Submit also runs 15 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Greedy with a three-letter scan | O(a + b + c) | O(1) |
| Optimal (max-heap greedy) | O(a + b + c) | O(1) |
1Greedy with a three-letter scan
O(a + b + c)Each step writes one letter and looks at only three candidates, and at most a + b + c letters are written.O(1)Three counters, apart from the answer string itself.Build the answer one letter at a time. At each step, look at the three letters and keep only those that still have copies left and would not make three in a row. Among them, write the one with the most copies left. If no letter is allowed, stop. Spending the most plentiful letter first keeps the other letters around as separators for as long as possible.
- Keep left = {a, b, c} and an empty builder.
- Repeat: for each letter k with left[k] > 0, skip it if the last two characters of the builder are both that letter.
- Among the letters not skipped, pick the one with the largest left[k]. If there is none, stop.
- Append the picked letter and subtract one from its count.
- Return the builder.
class Solution {
public String longestDiverseString(int a, int b, int c) {
int[] left = {a, b, c};
StringBuilder sb = new StringBuilder();
while (true) {
int pick = -1;
for (int k = 0; k < 3; k++) {
if (left[k] == 0) continue;
char ch = (char) ('a' + k);
int n = sb.length();
if (n >= 2 && sb.charAt(n - 1) == ch && sb.charAt(n - 2) == ch) continue;
if (pick == -1 || left[k] > left[pick]) pick = k;
}
if (pick == -1) break;
sb.append((char) ('a' + pick));
left[pick]--;
}
return sb.toString();
}
}class Solution:
def longestDiverseString(self, a: int, b: int, c: int) -> str:
left = [a, b, c]
out = []
while True:
pick = -1
for k in range(3):
if left[k] == 0:
continue
ch = chr(ord('a') + k)
if len(out) >= 2 and out[-1] == ch and out[-2] == ch:
continue
if pick == -1 or left[k] > left[pick]:
pick = k
if pick == -1:
break
out.append(chr(ord('a') + pick))
left[pick] -= 1
return "".join(out)class Solution {
public:
string longestDiverseString(int a, int b, int c) {
int left[3] = {a, b, c};
string sb;
while (true) {
int pick = -1;
for (int k = 0; k < 3; k++) {
if (left[k] == 0) continue;
char ch = (char)('a' + k);
int n = (int)sb.size();
if (n >= 2 && sb[n - 1] == ch && sb[n - 2] == ch) continue;
if (pick == -1 || left[k] > left[pick]) pick = k;
}
if (pick == -1) break;
sb.push_back((char)('a' + pick));
left[pick]--;
}
return sb;
}
};function longestDiverseString(a, b, c) {
const left = [a, b, c];
const sb = [];
while (true) {
let pick = -1;
for (let k = 0; k < 3; k++) {
if (left[k] === 0) continue;
const ch = String.fromCharCode(97 + k);
const n = sb.length;
if (n >= 2 && sb[n - 1] === ch && sb[n - 2] === ch) continue;
if (pick === -1 || left[k] > left[pick]) pick = k;
}
if (pick === -1) break;
sb.push(String.fromCharCode(97 + pick));
left[pick]--;
}
return sb.join("");
}2Optimal (max-heap greedy)
O(a + b + c)Each loop writes at most one letter, and every heap operation works on at most three entries, so it costs constant time.O(1)The heap never holds more than three entries; only the answer grows.Keep the letters that still have copies in a max-heap ordered by count, with ties broken by letter. Pop the top letter. If writing it would make three in a row, pop the next one instead, write that one, and push both back (the second only if copies remain). If the top letter is blocked and the heap has nothing else, stop: every remaining letter is the blocked one. The same idea works unchanged for any number of letters, which is why the heap is the usual way to write it.
- Push (count, letter) for every letter whose count is above zero.
- While the heap is not empty, pop first. If the builder does not end in two copies of first's letter, append it, lower its count, and push it back if the count is still above zero.
- Otherwise, if the heap is empty, stop. If not, pop second, append its letter, lower its count, push it back if any copies remain, and push first back unchanged.
- Return the builder.
class Solution {
public String longestDiverseString(int a, int b, int c) {
PriorityQueue<int[]> pq = new PriorityQueue<>((x, y) -> x[0] != y[0] ? y[0] - x[0] : x[1] - y[1]);
if (a > 0) pq.offer(new int[]{a, 0});
if (b > 0) pq.offer(new int[]{b, 1});
if (c > 0) pq.offer(new int[]{c, 2});
StringBuilder sb = new StringBuilder();
while (!pq.isEmpty()) {
int[] first = pq.poll();
char ch = (char) ('a' + first[1]);
int n = sb.length();
if (n >= 2 && sb.charAt(n - 1) == ch && sb.charAt(n - 2) == ch) {
if (pq.isEmpty()) break;
int[] second = pq.poll();
sb.append((char) ('a' + second[1]));
second[0]--;
if (second[0] > 0) pq.offer(second);
pq.offer(first);
} else {
sb.append(ch);
first[0]--;
if (first[0] > 0) pq.offer(first);
}
}
return sb.toString();
}
}class Solution:
def longestDiverseString(self, a: int, b: int, c: int) -> str:
pq = []
for cnt, k in ((a, 0), (b, 1), (c, 2)):
if cnt > 0:
heapq.heappush(pq, (-cnt, k))
out = []
while pq:
cnt, k = heapq.heappop(pq)
ch = chr(ord('a') + k)
if len(out) >= 2 and out[-1] == ch and out[-2] == ch:
if not pq:
break
cnt2, k2 = heapq.heappop(pq)
out.append(chr(ord('a') + k2))
cnt2 += 1
if cnt2 < 0:
heapq.heappush(pq, (cnt2, k2))
heapq.heappush(pq, (cnt, k))
else:
out.append(ch)
cnt += 1
if cnt < 0:
heapq.heappush(pq, (cnt, k))
return "".join(out)class Solution {
public:
string longestDiverseString(int a, int b, int c) {
// (count, -letter): the largest count first, ties go to the smaller letter
priority_queue<pair<int, int>> pq;
if (a > 0) pq.push({a, 0});
if (b > 0) pq.push({b, -1});
if (c > 0) pq.push({c, -2});
string sb;
while (!pq.empty()) {
pair<int, int> first = pq.top();
pq.pop();
char ch = (char)('a' - first.second);
int n = (int)sb.size();
if (n >= 2 && sb[n - 1] == ch && sb[n - 2] == ch) {
if (pq.empty()) break;
pair<int, int> second = pq.top();
pq.pop();
sb.push_back((char)('a' - second.second));
second.first--;
if (second.first > 0) pq.push(second);
pq.push(first);
} else {
sb.push_back(ch);
first.first--;
if (first.first > 0) pq.push(first);
}
}
return sb;
}
};function longestDiverseString(a, b, c) {
// at most three entries, so a small array kept sorted works as the max-heap
const pq = [];
const push = (e) => {
pq.push(e);
pq.sort((x, y) => (x[0] !== y[0] ? y[0] - x[0] : x[1] - y[1]));
};
if (a > 0) push([a, 0]);
if (b > 0) push([b, 1]);
if (c > 0) push([c, 2]);
const sb = [];
while (pq.length > 0) {
const first = pq.shift();
const ch = String.fromCharCode(97 + first[1]);
const n = sb.length;
if (n >= 2 && sb[n - 1] === ch && sb[n - 2] === ch) {
if (pq.length === 0) break;
const second = pq.shift();
sb.push(String.fromCharCode(97 + second[1]));
second[0]--;
if (second[0] > 0) push(second);
push(first);
} else {
sb.push(ch);
first[0]--;
if (first[0] > 0) push(first);
}
}
return sb.join("");
}Edge cases to test
- Only one letter available: the answer is that letter once or twice
- One count far larger than the other two, so some letters must be left unused
- All three counts equal, so every letter can be used
- A count of zero for one or two letters
- Counts that are almost too large, such as a = 2 * (b + c + 1), where every letter still fits
- Ties between counts, where any of the tied letters may be picked
Hints
Hint 1
Build the string one letter at a time. Which letter is the most dangerous to leave for the end?
Hint 2
Always try to write the letter with the most copies left. The only time you cannot is when the last two letters are already that letter.
Hint 3
In that case write the letter with the second most copies, then go back to the largest one. A max-heap of (count, letter) pairs hands you the largest and the second largest quickly.
FAQ
What is the best time complexity for Longest Happy String?
Optimal (max-heap greedy) runs in O(a + b + c) time and O(1) extra space. Each loop writes at most one letter, and every heap operation works on at most three entries, so it costs constant time.
Which pattern does Longest Happy String use?
It is a heaps problem that uses the advanced pattern. Other problems with the same pattern: Find K Pairs with Smallest Sums, Find Median from Data Stream, Trapping Rain Water II.
Is there a brute force solution for Longest Happy String?
Yes. Greedy with a three-letter scan takes O(a + b + c) time and O(1) space. Build the answer one letter at a time.
Which edge cases should I test for Longest Happy String?
Only one letter available: the answer is that letter once or twice; One count far larger than the other two, so some letters must be left unused; All three counts equal, so every letter can be used; A count of zero for one or two letters; Counts that are almost too large, such as a = 2 (b + c + 1), where every letter still fits; Ties between counts, where any of the tied letters may be picked.