Check if All A's Appears Before All B's (LeetCode 2124): Solution and Explanation

Easy
String

Given a string of only 'a' and 'b' characters, decide whether every 'a' comes before every 'b'.

Intuition

A valid string looks like a block of a's followed by a block of b's, where either block may be empty. The only thing that can go wrong is an 'a' showing up after a 'b'.

So read the string once and remember a single fact: has a 'b' appeared yet? Before the first 'b', an 'a' is fine. After it, the first 'a' you meet is proof that the answer is false.

Approach: Single scan with a seen-b flag

  1. Set seenB = false.
  2. For each character: if it is 'b', set seenB = true.
  3. Otherwise it is 'a'. If seenB is already true, return false.
  4. If the loop finishes, return true.

Step-by-step example

s = "aaabbb"
  1. Indices 0, 1 and 2 are 'a' and no 'b' has been seen, so all three are fine.
  2. Index 3 is the first 'b'. Set seenB = true.
  3. Indices 4 and 5 are also 'b', which is allowed after a 'b'.
  4. The scan ends without an 'a' after a 'b', so the answer is true.

Code: Python, Java, C++

1class Solution:
2    def checkString(self, s: str) -> bool:
3        seen_b = False
4        for c in s:
5            if c == 'b':
6                seen_b = True
7            elif seen_b:
8                return False
9        return True
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Each character is read at most once, and the scan can stop early on failure.

Space

O(1)

Only one boolean flag is kept.

Other approaches

Search for "ba" (time O(n), space O(1))

An 'a' comes after some 'b' exactly when the string contains the pair "ba" next to each other, so "ba" not in s is the answer. Short and also linear.

Compare the last 'a' with the first 'b' (time O(n), space O(1))

Find the last index of 'a' and the first index of 'b'. The answer is true if either is missing or the last 'a' is before the first 'b'.

Common mistakes

  • Returning false for a string with no 'a' or no 'b'. Both "bbb" and "aaa" are valid.
  • Resetting the flag when another 'a' is read. Once a 'b' has appeared, the flag must stay set.
  • Checking only that the string starts with 'a' and ends with 'b', which wrongly accepts "abab".

Frequently asked questions

Why is checking for "ba" enough?

If some 'a' comes after some 'b', then somewhere between them a 'b' is immediately followed by an 'a', which is the pair "ba". If no such pair exists, the string is a run of a's followed by a run of b's.

Is a string of only b's valid?

Yes. There is no 'a' that could appear after a 'b', so the condition holds.

Can the scan stop early?

Yes. The first 'a' after a 'b' settles the answer as false, so there is no need to read the rest.