Check if All A's Appears Before All B's - Problem

Given a string s consisting of only the characters 'a' and 'b', return true if every 'a' appears before every 'b' in the string. Otherwise, return false.

In other words, the string should have all 'a' characters grouped together at the beginning (or none at all), followed by all 'b' characters grouped together at the end (or none at all).

Input & Output

Example 1 — All a's before all b's
$ Input: s = "aaabbb"
Output: true
💡 Note: All 'a' characters (positions 0,1,2) appear before all 'b' characters (positions 3,4,5)
Example 2 — Mixed pattern
$ Input: s = "abab"
Output: false
💡 Note: The 'a' at position 2 appears after the 'b' at position 1, violating the pattern
Example 3 — Only one character type
$ Input: s = "aaa"
Output: true
💡 Note: String contains only 'a' characters, so the pattern is valid

Constraints

  • 1 ≤ s.length ≤ 100
  • s[i] is either 'a' or 'b'

Visualization

Tap to expand
Check if All A's Appear Before All B'sValid: aaabbbaaabbb✓ All a's before all b'sInvalid: abababab✗ 'a' appears after 'b'Algorithm: Single Pass State Tracking1. Scan left to right2. Track if we've seen 'b' character3. If 'a' appears after seeing 'b', return falseTime: O(n) | Space: O(1)
Understanding the Visualization
1
Input
String containing only 'a' and 'b' characters
2
Check Pattern
Verify all 'a's come before all 'b's
3
Output
Return true if pattern is valid, false otherwise
Key Takeaway
🎯 Key Insight: Once you see a 'b', no 'a' should appear afterward for a valid pattern
Asked in
Apple 15 Microsoft 12
28.5K Views
Medium Frequency
~8 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen