String Without Aaa Or Bbb Problem
Description
LeetCode Problem 984.
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.
Solution
Approach: Greedy, Write the More Frequent Letter
The danger is running out of the rarer letter while many copies of the other one are left: with a = 4, b = 1, starting "abaa" leaves two as that can no longer be placed. So spend the letter we have more of as early as the rules allow, and use the other letter only as a separator.
Build the string one letter at a time while a > 0 or b > 0:
- If the last two letters are equal, we are forced: write the other letter (after
"aa"writeb, after"bb"writea). - Otherwise write
aifa >= b, elseb. - Decrease the count of the letter written.
This produces patterns like "aabaabaa": two of the frequent letter, one of the rare one. That is exactly the shape needed in the tightest case, where the larger count is twice the smaller count plus 2, so whenever a valid string exists the greedy never gets stuck.
The order of the checks matters: the "two in a row" rule must come first. Checking a >= b first would happily write a third a.
Complexity: O(a + b) time and O(a + b) space for the result.
class Solution:
def strWithout3a3b(self, a: int, b: int) -> str:
result = []
while a > 0 or b > 0:
if len(result) >= 2 and result[-1] == result[-2]:
# two equal letters in a row: the next one must be the other letter
write_a = result[-1] == "b"
else:
# otherwise use up the letter we have more of
write_a = a >= b
if write_a:
result.append("a")
a -= 1
else:
result.append("b")
b -= 1
return "".join(result)
Now write it from memory
Close the write-up and solve it yourself against the tests.