Check if All A's Appears Before All B's (LeetCode 2124): Solution and Explanation
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
- Set
seenB = false. - For each character: if it is 'b', set
seenB = true. - Otherwise it is 'a'. If
seenBis already true, returnfalse. - If the loop finishes, return
true.
Step-by-step example
s = "aaabbb"
- Indices 0, 1 and 2 are 'a' and no 'b' has been seen, so all three are fine.
- Index 3 is the first 'b'. Set seenB = true.
- Indices 4 and 5 are also 'b', which is allowed after a 'b'.
- 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 True1class Solution {
2 public boolean checkString(String s) {
3 boolean seenB = false;
4 for (char c : s.toCharArray()) {
5 if (c == 'b') {
6 seenB = true;
7 } else if (seenB) {
8 return false;
9 }
10 }
11 return true;
12 }
13}1class Solution {
2public:
3 bool checkString(string s) {
4 bool seenB = false;
5 for (char c : s) {
6 if (c == 'b') {
7 seenB = true;
8 } else if (seenB) {
9 return false;
10 }
11 }
12 return true;
13 }
14};Time and space complexity
O(n)
Each character is read at most once, and the scan can stop early on failure.
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.