LeetCode solutions

1026. String Without AAA or BBB

My accepted Python solution to LeetCode problem 1026, String Without AAA or BBB, running in 38ms.

  • Difficulty: Medium
  • Python
  • Runtime 38ms
  • Memory 17.1MB

Read the problem on LeetCode View on GitHub

Python

Accepted on LeetCode — runtime 38ms, memory 17.1MB, accepted 2026-01-02.

python
class Solution:
    def strWithout3a3b(self, a: int, b: int) -> str:
        result = []
        
        while a > 0 or b > 0:
            # Check last two chars
            if len(result) >= 2 and result[-1] == result[-2]:
                # Need to add the other char
                if result[-1] == 'a':
                    result.append('b')
                    b -= 1
                else:
                    result.append('a')
                    a -= 1
            else:
                # Add char with larger count
                if a >= b:
                    result.append('a')
                    a -= 1
                else:
                    result.append('b')
                    b -= 1
        
        return ''.join(result)

Source