Intuition
Every 'a' before every 'b' is exactly the same as saying the pattern 'ba' never happens. Scan once from left to right: the moment you pass a 'b', any later 'a' is out of order and the answer is false.
Explanation
Building intuition
We never need to compare pairs of characters. Think about what breaks the rule: the first time a 'b' is followed (anywhere later) by an 'a'. That is the two-character pattern 'ba' appearing in the string. So the whole question reduces to: does 'ba' ever occur? If it never does, every 'a' sits before every 'b'.
Steps
- Walk through the string once, left to right, keeping a single flag
seen_bthat starts asfalse. - When the current character is
'b', setseen_b = true. From here on, a 'b' is behind us. - When the current character is
'a', checkseen_b. If it is alreadytrue, this 'a' comes after a 'b', so returnfalseimmediately. - If the loop finishes without ever hitting that case, return
true.
Walk-through
s = "aaabba":
| index | char | seen_b before | action |
|---|---|---|---|
| 0 | a | false | ok, no 'b' yet |
| 1 | a | false | ok |
| 2 | a | false | ok |
| 3 | b | false | set seen_b = true |
| 4 | b | true | still fine, it's a 'b' |
| 5 | a | true | 'a' after a 'b' → return false |
Answer: false. ✓
Now s = "aaabbb": the first three characters are 'a' (seen_b stays false), then three 'b's flip and keep seen_b = true, and no 'a' ever follows. The loop ends and we return true. ✓
And s = "bbb": there are no 'a's at all, so the seen_b check is never triggered and we return true. ✓
Edge cases
- No 'a's (e.g.
"bbb") or no 'b's (e.g."aaa"): nothing can be out of order, so the answer istrue. - Single character:
"a"and"b"are bothtrue. - The first
'b'only arms the check. A later'a'is what fails it.
Complexity
- Time: O(n). One pass over the string.
- Space: O(1). One boolean flag.
Implementation
class Solution {
public boolean checkString(String s) {
boolean seenB = false;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == 'b') {
seenB = true;
} else if (seenB) {
return false;
}
}
return true;
}
}