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: "ccaccbcc"
💡 Note: We have 7 c's, 1 a, and 1 b. Using a greedy approach: add cc, then a (to avoid 3 c's), then cc, then b, then cc. Result: ccaccbcc uses 6 c's, 1 a, 1 b = 8 characters total.
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 - Greedy Approach INPUT a 1 b 1 c 7 Constraints: NO "aaa", "bbb", "ccc" Only 'a', 'b', 'c' allowed Maximize string length Initial Priority (by count): c: 7 (highest) a: 1 b: 1 ALGORITHM STEPS 1 Use Max Heap Sort chars by remaining count 2 Pick Max Char Check: won't create "xxx" 3 Add to Result Decrement count, re-heap 4 Repeat / Switch If blocked, use 2nd max Build Trace: Step Result Remaining 1 "cc" a:1 b:1 c:5 2 "ccb" a:1 b:0 c:5 3 "ccbcc" a:1 b:0 c:3 4 "ccbcca" a:0 b:0 c:3 5 "ccbccac" a:0 b:0 c:2 STOP: can't add more c's (remaining c:2 blocked) FINAL RESULT Happy String: c c b c c a c Output: "ccbccac" Verification: [OK] Length: 7 characters [OK] a count: 1 (max 1) [OK] b count: 1 (max 1) [OK] c count: 5 (max 7) [OK] No "aaa", "bbb", "ccc" Valid Happy String! Key Insight: Greedy works because we always pick the character with the highest remaining count, unless it would create three consecutive same characters. In that case, we use the second-highest to "break" the sequence. This maximizes length while staying valid. TutorialsPoint - Longest Happy String | Greedy Approach
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