Check if All A's Appears Before All B's
LeetCode 2243 | Difficulty: Easyβ
EasyProblem Descriptionβ
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.
Example 1:
Input: s = "aaabbb"
Output: true
Explanation:
The 'a's are at indices 0, 1, and 2, while the 'b's are at indices 3, 4, and 5.
Hence, every 'a' appears before every 'b' and we return true.
Example 2:
Input: s = "abab"
Output: false
Explanation:
There is an 'a' at index 2 and a 'b' at index 1.
Hence, not every 'a' appears before every 'b' and we return false.
Example 3:
Input: s = "bbb"
Output: true
Explanation:
There are no 'a's, hence, every 'a' appears before every 'b' and we return true.
Constraints:
- `1 <= s.length <= 100`
- `s[i]` is either `'a'` or `'b'`.
Topics: String
Approachβ
String Processingβ
Consider character frequency counts, two-pointer approaches, or building strings efficiently. For pattern matching, think about KMP or rolling hash. For palindromes, expand from center or use DP.
When to use
Anagram detection, palindrome checking, string transformation, pattern matching.
Solutionsβ
Solution 1: C# (Best: 68 ms)β
| Metric | Value |
|---|---|
| Runtime | 68 ms |
| Memory | 38.5 MB |
| Date | 2022-02-13 |
Solution
public class Solution {
public bool CheckString(string s) {
int i =0, maxA = -1;
for (; i < s.Length; i++)
{
if(s[i] == 'b') break;
}
while(++i<s.Length)
{
if(s[i]=='a') return false;
}
return true;
}
}
Complexity Analysisβ
| Approach | Time | Space |
|---|---|---|
| Solution | $O(n)$ | $O(1) to O(n)$ |
Interview Tipsβ
Key Points
- Start by clarifying edge cases: empty input, single element, all duplicates.
- LeetCode provides 2 hint(s) for this problem β try solving without them first.
π‘ Hints
Hint 1: You can check the opposite: check if there is a βbβ before an βaβ. Then, negate and return that answer.
Hint 2: s should not have any occurrences of βbaβ as a substring.