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's INPUT String s = "aaabbb" a i=0 a i=1 a i=2 b i=3 b i=4 b i=5 'a' characters 'b' characters Pattern: aaa | bbb All a's grouped, then all b's s = "aaabbb" ALGORITHM STEPS 1 Initialize Track if 'b' has been seen seenB = false 2 Iterate String Scan each character once for char in s: 3 Check Pattern If 'b' seen and current is 'a' if seenB and c=='a': false 4 Update Flag Mark when 'b' is encountered if c=='b': seenB = true Scan: a-->a-->a-->b-->b-->b No 'a' found after any 'b' Time: O(n) | Space: O(1) FINAL RESULT Valid Pattern aaa | bbb All 'a' characters appear before all 'b' characters No 'ba' pattern found Pattern is VALID OK Output: true Key Insight: The string is valid if and only if it doesn't contain the substring "ba". Once we see a 'b', any subsequent 'a' would violate the rule. Single pass with early termination achieves O(n) time. TutorialsPoint - Check if All A's Appears Before All B's | Single Pass - Early Detection
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