Taro Logo

String Without AAA or BBB

#1 Most AskedMedium
6 views
Topics:
StringsGreedy Algorithms

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


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What are the constraints on the input integers $A$ (number of 'a's) and $B$ (number of 'b's)? Can they be zero, and what is the maximum value they can take?
  2. Is it guaranteed that a valid solution always exists for the given inputs $A$ and $B$, or do we need to handle cases where it's impossible to form a valid string?
  3. If multiple valid strings can be formed using all the given 'a's and 'b's, does the interviewer prefer any specific one, or is returning any valid string acceptable?
  4. Should we always use all of the given $A$ 'a's and $B$ 'b's, or is it permissible to leave some characters unused if necessary?
  5. Can the return type simply be a standard string, and does memory allocation for the output string need to be handled in any specific way?

Brute Force Solution

Approach

Imagine you have a pile of letter blocks, some shaped like the letter A and some shaped like the letter B, and your goal is to line them up following a specific rule without placing three of the same letter right next to each other. The brute force strategy involves testing every conceivable ordering of all the available letter blocks to see which arrangement successfully obeys the rule.

Here's how the algorithm would work step-by-step:

  1. Start by gathering the exact total number of letter blocks you are given.
  2. Generate a completely random sequence using all of those letter blocks from start to finish.
  3. Examine this sequence closely to check if three identical letters ever sit right next to each other anywhere in the line.
  4. If you find three matching letters touching, throw that sequence away because it breaks the rule.
  5. If the sequence manages to avoid having three matching letters in a row, keep it as a valid solution.
  6. Since there are many ways to arrange the blocks, repeat the process by building and testing every other possible arrangement one by one until you have checked them all.
  7. Finally, pick any one of the valid sequences you found during your search to present as your successful answer.

Code Implementation

import itertools


def strWithout3a3b(count_a, count_b):
    total_blocks = count_a * "a" + count_b * "b"

    # Generate every unique permutation of letters to test all possible arrangements
    for candidate_seq in set(itertools.permutations(total_blocks)):
        current_seq = "".join(candidate_seq)

        # Check for three consecutive identical characters which violate the problem rule
        if "aaa" not in current_seq and "bbb" not in current_seq:
            return current_seq

    return ""

Big(O) Analysis

Time Complexity
O((A + B)!) – To determine the time complexity, let n equal the total number of blocks, which is A plus B. The brute force strategy requires generating and testing every conceivable permutation of these letter blocks. The total number of unique ways to arrange A and B blocks is given by the factorial of the sum, represented as (A + B)!. For each of these permutations, the algorithm must scan through the sequence to check for three identical adjacent letters. This leads to approximately (A + B)! * (A + B) operations, which simplifies to O((A + B)!) or O(n!).
Space Complexity
O(N) – To evaluate every conceivable ordering of the letter blocks, the algorithm must generate and store sequences of length N, where N is the total number of blocks (A plus B). Additionally, testing permutations implies keeping track of generation states and temporary trial strings of size N. Therefore, the auxiliary space scales linearly with the input size N, resulting in a space complexity of O(N).

Optimal Solution

Approach

The optimal strategy builds the output string letter by letter by always prioritizing the character of which we currently have the most remaining. It adds two of the dominant character at a time, unless doing so would violate the rule against having three identical characters in a row, in which case it temporarily places the other character.

Here's how the algorithm would work step-by-step:

  1. Count how many of the first letter and the second letter you need to place in total.
  2. Compare the two counts to see which letter you need to use more of right now.
  3. Whenever the first letter is much more frequent, safely add two of it to your growing result to use up the supply quickly.
  4. If the counts are tied, or if the second letter is more frequent, add just one of the more frequent letter instead.
  5. Whenever adding the preferred letter would create a forbidden run of three identical letters in a row, pivot and add one of the alternative letter to break the streak.
  6. Repeat this decision-making process step by step, constantly recalculating which letter is needed most, until all required letters have been successfully placed.

Code Implementation

def str_without3a3b(count_of_a, count_of_b):    result_characters = []        while count_of_a > 0 or count_of_b > 0:                # We need to determine if we should write two characters at once to consume the larger pool faster.        write_two_a = count_of_a >= count_of_b and count_of_a > 1 and result_characters[-2:] != ['a', 'a'] or result_characters[-2:] == ['b', 'b']                if write_two_a or (count_of_a > 0 and result_characters[-2:] != ['a', 'a'] and count_of_a >= count_of_b):            if result_characters[-2:] == ['a', 'a'] and count_of_b > 0:                result_characters.append('b')                count_of_b -= 1            else:                characters_to_add = min(2, count_of_a)                result_characters.extend(['a'] * characters_to_add)                count_of_a -= characters_to_add        else:                        # If 'b' is more frequent or we are forced to break an 'a' streak, we append 'b'.            if result_characters[-2:] == ['b', 'b'] and count_of_a > 0:                result_characters.append('a')                count_of_a -= 1            else:                characters_to_add = min(2, count_of_b)                result_characters.extend(['b'] * characters_to_add)                count_of_b -= characters_to_add                    return "".join(result_characters)

Big(O) Analysis

Time Complexity
O(a + b) – The total number of operations is directly driven by the sum of a and b, which represents the total length of the resulting string n. In each iteration of the construction process, we append either one or two characters to our result string until both a and b are exhausted. Since each step processes a constant number of characters and reduces the remaining supply by at most two, the loop executes roughly (a + b) / 2 times. Therefore, the operations scale linearly with the input sizes a and b, which simplifies to O(n) where n equals a plus b.
Space Complexity
O(N) – The algorithm builds a growing result string character by character to store the final output, where N represents the total number of characters equal to A plus B. This resulting string requires auxiliary memory that scales directly with the length of the input parameters. Aside from a few constant tracking variables for character counts, no other dynamic data structures or recursion stacks are utilized. Therefore, the extra memory used is entirely dominated by the storage of the output string itself, resulting in a linear space complexity.

Edge Cases

One of the counts is zero from the start
How to Handle:
The greedy choice logic will safely append the remaining characters up to two at a time until exhausted.
Both counts are zero
How to Handle:
The loop terminates immediately and returns an empty string.
Highly skewed distribution where a is much larger than b
How to Handle:
The algorithm prioritizes appending 'a' twice when it exceeds 'b', keeping the counts balanced without violating the triple rule.
Equal counts of a and b
How to Handle:
The greedy condition comparing remaining counts will alternate characters smoothly.
Counts are large enough to approach memory limits for string concatenation
How to Handle:
Using a string builder approach ensures efficient linear time construction without excessive object creation overhead.
Multiple valid solutions are possible
How to Handle:
The problem states any valid string is acceptable, so the deterministic greedy path returns one correct permutation.
0/2 completed