String Without AAA or BBB - Problem
Given two integers a and b, return any string s such that:
shas lengtha + band contains exactlya'a' letters, and exactlyb'b' letters- The substring
'aaa'does not occur ins - The substring
'bbb'does not occur ins
You need to construct a valid string that uses all the given characters while avoiding three consecutive identical characters.
Input & Output
Example 1 — Basic Case
$
Input:
a = 1, b = 2
›
Output:
"bab"
💡 Note:
We have 1 'a' and 2 'b's. Since b > a, we can start with 'b', then 'a', then 'b' to get "bab". No 'aaa' or 'bbb' patterns exist.
Example 2 — Equal Counts
$
Input:
a = 2, b = 1
›
Output:
"aab"
💡 Note:
We have 2 'a's and 1 'b'. Since a > b, we can place "aa" then "b" to get "aab". This uses all characters without forbidden patterns.
Example 3 — Large Difference
$
Input:
a = 1, b = 4
›
Output:
"bbabb"
💡 Note:
With 4 'b's and 1 'a', we need to carefully place 2 'b's, then 'a', then remaining 'b's to avoid 'bbb' pattern.
Constraints
- 0 ≤ a ≤ 100
- 0 ≤ b ≤ 100
- 1 ≤ a + b ≤ 100
Visualization
Tap to expand
Understanding the Visualization
1
Input
Given counts: a=1, b=2
2
Process
Build string avoiding 'aaa' and 'bbb'
3
Output
Valid string: "bab"
Key Takeaway
🎯 Key Insight: Always place the more abundant character first, but limit consecutive placements to at most 2
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code