#984

String Without AAA or BBB

Medium
StringGreedyGreedyTwo Pointers
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach uses a greedy strategy to construct the string directly by ensuring that we never create three consecutive 'a's or 'b's. This is efficient and avoids unnecessary checks.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize an empty result string.
  2. 2Step 2: While there are still 'a's or 'b's left, append 'a' or 'b' to the result based on their counts.
  3. 3Step 3: If appending 'a' would create 'aaa', append 'b' instead, and vice versa.
  4. 4Step 4: Continue until all 'a's and 'b's are used.
solution.py24 lines
1def generate_string(a, b):
2    result = []
3    while a > 0 or b > 0:
4        if a > b:
5            if a > 1:
6                result.append('aa')
7                a -= 2
8            else:
9                result.append('a')
10                a -= 1
11            if b > 0:
12                result.append('b')
13                b -= 1
14        else:
15            if b > 1:
16                result.append('bb')
17                b -= 2
18            else:
19                result.append('b')
20                b -= 1
21            if a > 0:
22                result.append('a')
23                a -= 1
24    return ''.join(result)

Complexity note: The time complexity is O(n) since we are constructing the string in a single pass, and the space complexity is O(n) for the resulting string.

  • 1Using a greedy approach allows us to construct the string without backtracking.
  • 2Maintaining the balance between 'a's and 'b's helps avoid invalid substrings.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.