Skip to main content

String Without AAA or BBB - Solution & Explanation

MediumStringGreedy15 min readAsked at: Amazon, Google, Zalando
Practice this problem

Problem Statement

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, and
  • The substring 'bbb' does not occur in s.

 

Example 1:

Input: a = 1, b = 2
Output: "abb"
Explanation: "abb", "bab" and "bba" are all correct answers.

Example 2:

Input: a = 4, b = 1
Output: "aabaa"

 

Constraints:

  • 0 <= a, b <= 100
  • It is guaranteed such an s exists for the given a and b.

Approach Overview

Problem Overview: You are given two integers a and b representing how many times characters 'a' and 'b' must appear in a string. The goal is to construct any valid string that uses all characters while avoiding the substrings "aaa" and "bbb".

Approach 1: Greedy Approach with Alternating Strategy (O(a+b) time, O(1) space)

This approach builds the string one character at a time using a greedy rule. At each step, compare the remaining counts of a and b. Prefer the character with the larger remaining count, but only if adding it will not create three consecutive identical characters. If the last two characters in the result are the same, force the other character even if its count is smaller. The key insight is that always consuming the more frequent character keeps the distribution balanced while the consecutive check prevents invalid triples.

You maintain a growing result buffer and check the last two characters before appending. Each iteration reduces either a or b, so the loop runs exactly a + b times. This greedy constraint handling ensures the string never forms "aaa" or "bbb". The algorithm uses constant auxiliary memory besides the output string. This pattern commonly appears in greedy scheduling and balancing problems.

Approach 2: Interleaving Strategy (O(a+b) time, O(1) space)

The interleaving strategy first determines which character occurs more frequently. Suppose a > b. You place blocks like "aab" repeatedly while the difference between counts is large, then switch to alternating patterns like "ab" once the counts become closer. The idea is to distribute the dominant character across the entire string so it never forms three consecutive occurrences.

This technique effectively spreads the majority character in controlled groups of at most two before inserting the minority character. You continue until one character runs out, then append the remaining characters while respecting the two‑character limit. Because each character is appended once, the runtime remains linear in the final string length. This approach is essentially a structured version of the greedy idea and works well for problems involving constrained string construction and pattern avoidance.

Recommended for interviews: The greedy alternating strategy is what interviewers typically expect. It demonstrates that you can enforce constraints dynamically while building the result. Explaining why you prioritize the character with the larger remaining count—and how the last two characters prevent illegal triples—shows strong reasoning about greedy algorithms. The interleaving approach also works, but the dynamic greedy check is usually clearer and easier to implement under interview pressure.

Approach 1: Greedy Approach with Alternating Strategy

This approach constructs the string by always choosing the majority character until we need to switch to prevent three consecutive characters.

Steps:

  1. Determine which character ('a' or 'b') is more prevalent.
  2. Alternate placing two of the more prevalent character with one of the less prevalent character.
  3. Continue this until all characters are used up, ensuring that neither 'aaa' nor 'bbb' are formed.

This C solution uses a static buffer result which is filled character by character based on the remaining count of 'a's and 'b's. The decision on whether to append 'a' or 'b' depends on the count of the last two characters, as well as the overall remaining count of 'a' and 'b'.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(a + b) because each character is processed once.
Space Complexity: O(a + b) for the result string.

Try this approach in the editor →

Approach 2: Interleaving Strategy

This approach leverages an interleaving strategy to distribute characters evenly and avoid consecutive identical sequences.

Steps:

  1. Always append one of the more frequent character followed by the less frequent one until one type is exhausted.
  2. Finish by appending remaining characters in such a way that no prohibited sequence occurs.

This C solution follows a clear pattern by interleaving the characters carefully based on their counts. It constructs the string by focusing on avoiding 'aaa' or 'bbb' through interleaving up to two of the more frequent characters with one of the weaker.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(a + b) due to iteration through characters.
Space Complexity: O(a + b) used for the output string.

Try this approach in the editor →

Approach 3: Default Approach

Code

Python

Java

C++

Go

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Greedy Approach with Alternating Strategy

Time Complexity: O(a + b) because each character is processed once.
Space Complexity: O(a + b) for the result string.

Interleaving Strategy

Time Complexity: O(a + b) due to iteration through characters.
Space Complexity: O(a + b) used for the output string.

Default Approach—

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Greedy Approach with Alternating StrategyO(a+b)O(1)General case; easiest interview implementation with dynamic constraint checks
Interleaving StrategyO(a+b)O(1)When constructing structured patterns like "aab" or "bba" to distribute the majority character

Video Solution

LeetCode 984. String Without AAA or BBB Explanation and Solution • happygirlzt • 1,767 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is String Without AAA or BBB easy or hard?
LeetCode classifies the problem as Medium. The implementation is short, but the challenge is recognizing the greedy rule that balances the counts while preventing three identical characters in a row.
String Without AAA or BBB Python/Java solution
Both Python and Java implementations follow the same greedy pattern. Maintain counters for 'a' and 'b', repeatedly append the character with the larger count, and check the last two characters of the result before adding another. The loop continues until all characters are used.
How to solve String Without AAA or BBB in O(n)?
Treat n as a+b. Use a greedy rule while constructing the string: prefer the character with the larger remaining count, but check the last two characters of the result. If adding that character would form 'aaa' or 'bbb', append the other character instead. Each iteration consumes one character, resulting in linear time.
What is the best approach for String Without AAA or BBB?
The greedy alternating strategy is the most practical solution. Always append the character with the larger remaining count unless it would create three consecutive identical characters. If the last two characters are the same, force the other character. This builds the string in O(a+b) time with O(1) extra space.
Is String Without AAA or BBB asked at Google/Amazon/Meta?
Variants of constrained string construction problems appear in interviews at companies like Google, Amazon, and Meta. Interviewers use them to evaluate greedy decision making and the ability to enforce constraints while building sequences.
What data structure is used in String Without AAA or BBB?
The solution mainly uses a mutable string builder or array buffer to append characters efficiently. Only two counters track the remaining 'a' and 'b' characters, and a quick check of the last two characters prevents invalid triples.
What is the time complexity of String Without AAA or BBB?
The optimal algorithms run in O(a+b) time because each step appends exactly one character and the final string length is a+b. Space complexity is O(1) excluding the output string since only counters and a few checks on the last characters are required.

Ready to solve this problem?

Practice String Without AAA or BBB with our built-in code editor and test cases.

Practice on FleetCode