Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Check if All A's Appears Before All B's

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "2124" 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 a string s consisting of only the characters 'a' and 'b', return true if every 'a' appears before every 'b' in the string. Otherwise, return false. Example 1: Input: s = "aaabbb" Output: true Explanation: The 'a's are at indices 0, 1, and 2, while the 'b's are at indices 3, 4, and 5. Hence, every 'a' appears before every 'b' and we return true. Example 2: Input: s = "abab" Output: false Explanation: There is an 'a' at index 2 and a 'b' at index 1. Hence, not every 'a' appears before every 'b' and we return false. Example 3: Input: s = "bbb" Output: true Explanation: There are no 'a's, hence, every 'a' appears before every 'b' and we return true. Constraints: 1 <= s.length <= 100 s[i] is either 'a' or 'b'.

Explanation

Here's the breakdown of the solution:

  • Find the Last 'a': Iterate through the string to find the index of the last occurrence of 'a'. If no 'a' is found, the condition is trivially satisfied.
  • Check for 'b' After Last 'a': After finding the last 'a', iterate through the rest of the string. If a 'b' is encountered, return true. If a further 'a' is found after last 'a', then return false.
  • Trivial Case: If the loop completes without finding an 'a' or finding a 'b' after the last 'a', it means all 'a's appear before 'b's (or there are no 'a's), so return true.

  • Runtime Complexity: O(n) - where n is the length of the string. Storage Complexity: O(1) - constant extra space.

Code

    def checkString(s: str) -> bool:
    last_a_index = -1
    for i in range(len(s)):
        if s[i] == 'a':
            last_a_index = i

    if last_a_index == -1:
        return True

    for i in range(last_a_index + 1, len(s)):
        if s[i] == 'a':
            return False
    return True

More from this blog

C

Chatmagic blog

2894 posts