Check if All A's Appears Before All B's — LeetCode 2124 Python Solution
- Problem
- #2124
- Pattern
- Hash Map
- Reading time
- 2 min
- Source
- leetcode.com
The 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.
Example
- 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.
Python solution
class Solution:
def checkString(self, s: str) -> bool:
return "ba" not in sComplexity
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the length of the string s |
| Space | O(1) auxiliary |
Pattern: Hash Map
Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 2124. Check if All A's Appears Before All B's is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.
The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2124. Check if All A's Appears Before All B's?
- LeetCode 2124. Check if All A's Appears Before All B's is rated Easy on LeetCode.
- What is the time complexity of LeetCode 2124. Check if All A's Appears Before All B's?
- The Python solution on this page runs in O(n), where n is the length of the string s.
- What is the space complexity of LeetCode 2124. Check if All A's Appears Before All B's?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 2124. Check if All A's Appears Before All B's cover?
- LeetCode 2124. Check if All A's Appears Before All B's is tagged String on LeetCode.