Check if All A's Appears Before All B's
EasyUpdated: Jul 3, 2025
Practice on:
Problem
Given a string s consisting of only the characters 'a' and 'b', return true _ifevery _'a' _appears beforeevery _'b'in the string. Otherwise, return false.
Examples
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 <= 100s[i]is either'a'or'b'.
Solution
Method 1 – Single Pass with State Tracking
Intuition
We want to ensure that no 'a' appears after any 'b'. As we scan the string, once we see a 'b', any subsequent 'a' would violate the rule. We can use a flag to track if a 'b' has been seen.
Approach
- Initialize a flag to indicate if a 'b' has been seen.
- Iterate through the string:
- If the current character is 'b', set the flag.
- If the current character is 'a' and the flag is set, return false.
- If the loop completes, return true.
Code
Java
class Solution {
public boolean checkString(String s) {
boolean seenB = false;
for (char c : s.toCharArray()) {
if (c == 'b') seenB = true;
if (c == 'a' && seenB) return false;
}
return true;
}
}
Python
class Solution:
def checkString(self, s: str) -> bool:
seen_b = False
for c in s:
if c == 'b':
seen_b = True
if c == 'a' and seen_b:
return False
return True
Complexity
- ⏰ Time complexity:
O(n), wherenis the length of the string. - 🧺 Space complexity:
O(1)