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 Without AAA or BBB INPUT a = 1 'a' count b = 2 'b' count Available Letters: a b b Constraints: No "aaa" substring No "bbb" substring Target length: a + b = 3 ALGORITHM STEPS 1 Compare counts b(2) > a(1), pick 'b' result = "b" | a=1, b=1 2 Avoid "bb" repeat a(1) >= b(1), pick 'a' result = "ba" | a=0, b=1 3 Only 'b' remaining b(1) > a(0), pick 'b' result = "bab" | a=0, b=0 4 Verify result No "aaa" or "bbb" -- OK Greedy Rule: Pick char with higher count first FINAL RESULT Output String: b a b [0] [1] [2] Output: "bab" Verification: Length: 3 = 1 + 2 OK Count of 'a': 1 OK Count of 'b': 2 OK No "aaa"/"bbb" OK Key Insight: The greedy approach always picks the character with more remaining count. If the last two characters are the same, we must switch to the other character to avoid three consecutive. This ensures we use all characters while maintaining the constraint. Time: O(a+b), Space: O(a+b) TutorialsPoint - String Without AAA or BBB | Greedy Construction
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