984. String Without AAA or BBB LeetCode Solution
In this guide, you will get 984. String Without AAA or BBB LeetCode Solution with the best time and space complexity. The solution to String Without AAA or BBB problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- String Without AAA or BBB solution in C++
- String Without AAA or BBB solution in Java
- String Without AAA or BBB solution in Python
- Additional Resources
Problem Statement of String Without AAA or BBB
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.
Complexity Analysis
- Time Complexity: O(n)
- Space Complexity: O(n)
984. String Without AAA or BBB LeetCode Solution in C++
class Solution {
public:
string strWithout3a3b(int A, int B, char a = 'a', char b = 'b') {
if (A < B)
return strWithout3a3b(B, A, b, a);
if (B == 0)
return string(min(A, 2), a);
const int useA = min(A, 2);
const int useB = (A - useA >= B) ? 1 : 0;
return string(useA, a) + string(useB, b) +
strWithout3a3b(A - useA, B - useB, a, b);
}
};
/* code provided by PROGIEZ */
984. String Without AAA or BBB LeetCode Solution in Java
N/A
// code provided by PROGIEZ
984. String Without AAA or BBB LeetCode Solution in Python
N/A
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.