Check if All A's Appears Before All B's — LeetCode 2124 Python Solution

EasyString
Problem
#2124
Pattern
Hash Map
Reading time
2 min

The problem

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

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.

Python solution

Python
class Solution:
    def checkString(self, s: str) -> bool:
        return "ba" not in s

Complexity

MeasureComplexity
TimeO(n), where n is the length of the string s
SpaceO(1) auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 2124. Check if All A's Appears Before All B's is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2124. Check if All A's Appears Before All B's?
LeetCode 2124. Check if All A's Appears Before All B's is rated Easy on LeetCode.
What is the time complexity of LeetCode 2124. Check if All A's Appears Before All B's?
The Python solution on this page runs in O(n), where n is the length of the string s.
What is the space complexity of LeetCode 2124. Check if All A's Appears Before All B's?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2124. Check if All A's Appears Before All B's cover?
LeetCode 2124. Check if All A's Appears Before All B's is tagged String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview