Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: String Without AAA or BBB

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "984" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

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, 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.

Explanation

Here's the breakdown of the solution:

  • Greedy Approach: Prioritize using the character with the higher count, but avoid creating "aaa" or "bbb".
  • Conditional Logic: If adding the character with the higher count would result in three consecutive identical characters, switch to the other character.
  • String Building: Efficiently construct the string character by character.

  • Runtime Complexity: O(a + b), Storage Complexity: O(a + b)

Code

    def solve():
    a = int(input())
    b = int(input())

    result = ""
    while a > 0 or b > 0:
        if a > b:
            if len(result) >= 2 and result[-1] == 'a' and result[-2] == 'a':
                if b > 0:
                    result += 'b'
                    b -= 1
                else:
                    result += 'a'
                    a -=1
            else:
                result += 'a'
                a -= 1
        else:
            if len(result) >= 2 and result[-1] == 'b' and result[-2] == 'b':
                if a > 0:
                    result += 'a'
                    a -= 1
                else:
                    result += 'b'
                    b -= 1
            else:
                result += 'b'
                b -= 1
    print(result)

solve()

More from this blog

C

Chatmagic blog

2894 posts