Check if All A's Appears Before All B's - Problem
Given a string s consisting of only the characters 'a' and 'b', determine if all occurrences of 'a' appear before all occurrences of 'b' in the string.
In other words, the string should follow the pattern where we have zero or more 'a' characters followed by zero or more 'b' characters. Return true if this pattern holds, otherwise return false.
Examples:
"aaabbb"→true(all a's before all b's)"abab"→false(a's and b's are mixed)"aaa"→true(only a's)"bbb"→true(only b's)
Input & Output
example_1.py — Basic Valid Pattern
$
Input:
s = "aaabbb"
›
Output:
true
💡 Note:
All 'a' characters appear before all 'b' characters, forming a valid pattern.
example_2.py — Invalid Mixed Pattern
$
Input:
s = "abab"
›
Output:
false
💡 Note:
There's an 'a' after a 'b' (at indices 2), which violates the required pattern.
example_3.py — Only A's
$
Input:
s = "aaa"
›
Output:
true
💡 Note:
Since there are no 'b' characters, all 'a's trivially appear before all 'b's.
Constraints
- 1 ≤ s.length ≤ 100
- s[i] is either 'a' or 'b'
- The string contains only lowercase letters 'a' and 'b'
Visualization
Tap to expand
Understanding the Visualization
1
Start Reading
Begin scanning the shelf from left to right
2
Track State
Remember when you first see a non-fiction book (b)
3
Detect Error
If you find a fiction book (a) after seeing non-fiction, shelf is incorrectly organized
4
Complete Scan
If no errors found, the shelf is properly organized
Key Takeaway
🎯 Key Insight: Use a boolean flag to track when we've seen the first 'b'. Any 'a' found after this point immediately indicates an invalid pattern, allowing for early termination and optimal O(n) performance.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code