#2124

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

Easy
StringString ManipulationTwo Pointers
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution leverages the idea that we can check for the presence of the substring 'ba'. If it exists, it means there is at least one 'a' after a 'b', which violates our condition. This is efficient and straightforward.

⚙️

Algorithm

3 steps
  1. 1Step 1: Check if the substring 'ba' exists in the string.
  2. 2Step 2: If 'ba' is found, return false.
  3. 3Step 3: If 'ba' is not found, return true.
solution.py4 lines
1# Full working Python code
2
3def checkOrder(s):
4    return 'ba' not in s

Complexity note: The time complexity is O(n) because we scan the string once to check for the substring 'ba'. The space complexity is O(1) since we are not using any additional data structures.

  • 1The problem can be simplified by checking for the presence of 'ba'.
  • 2Understanding string operations can lead to more efficient solutions.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.