String Without AAA or BBB - Solution & Explanation
Problem Statement
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, and - The substring
'bbb'does not occur ins.
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
sexists for the givenaandb.
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:
- Determine which character ('a' or 'b') is more prevalent.
- Alternate placing two of the more prevalent character with one of the less prevalent character.
- 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'.
Complexity
Time Complexity: O(a + b) because each character is processed once.
Space Complexity: O(a + b) for the result string.
Approach 2: Interleaving Strategy
This approach leverages an interleaving strategy to distribute characters evenly and avoid consecutive identical sequences.
Steps:
- Always append one of the more frequent character followed by the less frequent one until one type is exhausted.
- 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.
Complexity
Time Complexity: O(a + b) due to iteration through characters.
Space Complexity: O(a + b) used for the output string.
Approach 3: Default Approach
Try this approach in the editor →Complexity Comparison
| Approach | Complexity |
|---|---|
| Greedy Approach with Alternating Strategy | Time Complexity: O(a + b) because each character is processed once. |
| Interleaving Strategy | Time Complexity: O(a + b) due to iteration through characters. |
| Default Approach | — |
Detailed Complexity Analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Greedy Approach with Alternating Strategy | O(a+b) | O(1) | General case; easiest interview implementation with dynamic constraint checks |
| Interleaving Strategy | O(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?
String Without AAA or BBB Python/Java solution
How to solve String Without AAA or BBB in O(n)?
What is the best approach for String Without AAA or BBB?
Is String Without AAA or BBB asked at Google/Amazon/Meta?
What data structure is used in String Without AAA or BBB?
What is the time complexity of String Without AAA or BBB?
Ready to solve this problem?
Practice String Without AAA or BBB with our built-in code editor and test cases.
Practice on FleetCodeTable of Contents
Practice this problem
Open in Editor