String Without AAA or BBB - Problem

Given two integers a and b, return any string s such that:

  • s has length a + b and contains exactly a 'a' letters, and exactly b 'b' letters
  • The substring 'aaa' does not occur in s
  • The substring 'bbb' does not occur in s

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
String Construction: Build Without AAA or BBBInput: a=1, b=2a=1b=2Greedy Construction ProcessValid Output:bab"bab" - Length 3, no forbidden patterns✓ Uses exactly 1 'a' and 2 'b's ✓ No 'aaa' or 'bbb' substrings
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
Asked in
Google 35 Facebook 28 Amazon 22
34.5K Views
Medium Frequency
~15 min Avg. Time
892 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