Longest Happy String - Problem

A string s is called happy if it satisfies the following conditions:

  • s only contains the letters 'a', 'b', and 'c'.
  • s does not contain any of "aaa", "bbb", or "ccc" as a substring.
  • s contains at most a occurrences of the letter 'a'.
  • s contains at most b occurrences of the letter 'b'.
  • s contains at most c occurrences 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.

Input & Output

Example 1 — Basic Case
$ Input: a = 1, b = 1, c = 7
Output: "ccbccac"
💡 Note: We have 7 c's, 1 a, and 1 b. Start with most frequent 'c', then alternate to avoid three consecutive c's. Result uses all characters: c-c-b-c-c-a-c.
Example 2 — Equal Counts
$ Input: a = 2, b = 2, c = 1
Output: "aabbc"
💡 Note: With equal counts of a and b, we can use both twice. Pattern: a-a-b-b-c uses all characters optimally.
Example 3 — No Solution
$ Input: a = 0, b = 2, c = 1
Output: "bbc"
💡 Note: Only b and c available. We can create b-b-c without violating the three consecutive rule.

Constraints

  • 0 ≤ a, b, c ≤ 100
  • a + b + c > 0

Visualization

Tap to expand
Longest Happy String: Build Maximum Length Without Triple Charactersa: 1b: 1c: 7Input: Character CountsccbccacProcess: Greedy Selection (Avoid aaa, bbb, ccc)Output: "ccbccac" - Happy String of Length 7Uses all available characters optimally
Understanding the Visualization
1
Input
Character counts: a=1, b=1, c=7
2
Process
Greedily select highest count character, avoid three consecutive
3
Output
Happy string: "ccbccac" (length 9)
Key Takeaway
🎯 Key Insight: Always prioritize the most frequent character while strategically switching to avoid three consecutive repeats
Asked in
Facebook 25 Google 18 Amazon 15
89.0K Views
Medium Frequency
~25 min Avg. Time
1.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen