Similar Problems

Similar Problems not available

String Without Aaa Or Bbb - Leetcode Solution

Companies:

LeetCode:  String Without Aaa Or Bbb Leetcode Solution

Difficulty: Medium

Topics: greedy string  

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; The substring 'bbb' does not occur in S.

Solution: To solve this problem, we can take the following approach:

  1. Create an empty string res.
  2. Calculate the maximum frequency value of 'a' and 'b' that can occur. i.e. if A is 5 and B is 3, then the maximum frequency of 'a' can be 4 and the maximum frequency of 'b' can be 2.
  3. Initialize two variables, i and j, to be the frequency of 'a' and 'b' respectively. i.e. i = min(A, max_freq_a) and j = min(B, max_freq_b).
  4. Using a while loop, check if i or j is greater than 0. While i or j is greater than 0, add 'a' or 'b' characters to the res string in such a way that the maximum number of 'aaa' or 'bbb' substrings are avoided.
  5. If i and j are not equal, add the remaining characters to the res string. i.e. if i is greater than j, then add 'aa' to the res string until i is greater than j - 1, and vice versa.
  6. Return the final string res.

Python Code:

def strWithout3a3b(A: int, B: int) -> str: res = '' max_freq_a = int((2 * B + 2) / 3) max_freq_b = int((2 * A + 2) / 3) i, j = min(A, max_freq_a), min(B, max_freq_b) while i > 0 or j > 0: if i > j: res += 'aab' i -= 2 j -= 1 elif j > i: res += 'bba' j -= 2 i -= 1 else: res += 'ab' i -= 1 j -= 1 return res

String Without Aaa Or Bbb Solution Code

1