Check if All A's Appears Before All B's — Problem & Solution
Check if All A's Appears Before All B's solution explained: step-by-step approach, complexity and code in Python, Java, C++ and JavaScript. An easy problem.
Check if All A's Appears Before All B's is an easy coding problem on strings, asked in Amazon and TCS interviews.
- Difficulty: Easy
- Topics: Strings
- Asked at: Amazon, TCS
- Time limit: 2 s
- Memory limit: 256 MB
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
Problem statement
Given a string s consisting only of the letters 'a' and 'b', return true if every 'a' appears before every 'b'.
Example 1
Input: s = "aaabbb"
Output: true
Example 2
Input: s = "abab"
Output: false
Explanation: The second a comes after the first b.
Example 3
Input: s = "bbb"
Output: true
Explanation: There are no a's, so the condition holds vacuously.
Constraints
1 <= s.length <= 100s consists only of the letters 'a' and 'b'.
Hints for Check if All A's Appears Before All B's
Hint 1
Once you have seen a
'b', no'a'may follow.Hint 2
One boolean flag is enough state.
Hint 3
Equivalently: the string must not contain
"ba"as a substring.
How to solve Check if All A's Appears Before All B's
The condition fails exactly when an 'a' appears after some 'b' — that is, when "ba" occurs. A single flag detects it in one pass.
Approach
- Start with
seenB = false. - Scan the string: on a
'b', setseenB = true. - On an
'a', returnfalseifseenBis already set. - Return
trueif the scan finishes.
Why it works
"Every a before every b" is violated precisely when some a follows some b, and by transitivity the earliest such violation involves adjacent-in-order characters — which the flag catches.
Complexity
- Time —
O(n) - Space —
O(1)
Pitfalls
- Counting a's and b's is not enough — the order matters, not the totals.
- Strings of only a's or only b's must both return
true.
Reference solution
Python
def checkString(s: str) -> bool:
return "ba" not in sJava
public static boolean checkString(String s) {
boolean seenB = false;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == 'b') seenB = true;
else if (seenB) return false;
}
return true;
}C++
bool checkString(string s) {
bool seenB = false;
for (char c : s) {
if (c == 'b') seenB = true;
else if (seenB) return false;
}
return true;
}JavaScript
var checkString = function(s) {
let seenB = false;
for (let i = 0; i < s.length; i++) {
if (s.charAt(i) === "b") seenB = true;
else if (seenB) return false;
}
return true;
};Also on the editorial tab: C, C#, Go, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.
All 515 strings problems · the whole catalogue
Learn the technique: Strings