Longest Happy String - Problem
The Longest Happy String Challenge
Imagine you're a string composer tasked with creating the longest possible "happy" string using only the characters
What makes a string happy?
๐ต It only contains letters
๐ซ It never contains three consecutive identical characters (no
๐ It respects the maximum usage limits for each character
Your mission: Given three integers representing the maximum number of
Example: With limits
Imagine you're a string composer tasked with creating the longest possible "happy" string using only the characters
'a', 'b', and 'c'. But there's a catch - your string has strict happiness rules!What makes a string happy?
๐ต It only contains letters
'a', 'b', and 'c'๐ซ It never contains three consecutive identical characters (no
"aaa", "bbb", or "ccc")๐ It respects the maximum usage limits for each character
Your mission: Given three integers representing the maximum number of
'a's, 'b's, and 'c's you can use, craft the longest possible happy string. If multiple solutions exist, any valid one works. If no happy string is possible, return an empty string.Example: With limits
a=1, b=1, c=7, you might create "ccaccbcc" or "ccbccacc" - both are valid happy strings of length 8! Input & Output
example_1.py โ Basic Case
$
Input:
a = 1, b = 1, c = 7
โบ
Output:
"ccaccbcc"
๐ก Note:
With 7 c's, 1 a, and 1 b, we can create a string of length 9. We use c's greedily but avoid three consecutive by inserting a's and b's strategically.
example_2.py โ Balanced Case
$
Input:
a = 2, b = 2, c = 1
โบ
Output:
"aabbc"
๐ก Note:
More balanced counts allow for a simpler pattern. We can use pairs of abundant characters followed by singles.
example_3.py โ Edge Case
$
Input:
a = 7, b = 1, c = 0
โบ
Output:
"aabaa"
๐ก Note:
With only two character types available, we use them optimally while avoiding three consecutive a's.
Constraints
- 0 โค a, b, c โค 100
- At least one of a, b, c must be positive for non-empty result
- No three consecutive identical characters allowed
Visualization
Tap to expand
Understanding the Visualization
1
Setup Priority Queue
Initialize max-heap with character counts: [7:c, 1:b, 1:a]
2
Pick Abundant Character
Select 'c' and add "cc" since count is much higher than others
3
Strategic Switch
Can't add another 'c', so switch to second most abundant 'b'
4
Continue Pattern
Add 'c' again, then forced to use 'a', creating optimal length
5
Final Result
Constructed "ccbccacc" using all characters optimally
Key Takeaway
๐ฏ Key Insight: The greedy priority queue approach ensures optimal length by always choosing the most abundant character while strategically switching to prevent constraint violations. The algorithm achieves O(n) time complexity and produces the longest possible happy string.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code