2124. Check if All A’s Appears Before All B’s LeetCode Solution

In this guide, you will get 2124. Check if All A’s Appears Before All B’s LeetCode Solution with the best time and space complexity. The solution to Check if All A’s Appears Before All B’s problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Check if All A’s Appears Before All B’s solution in C++
  4. Check if All A’s Appears Before All B’s solution in Java
  5. Check if All A’s Appears Before All B’s solution in Python
  6. Additional Resources
2124. Check if All A's Appears Before All B's LeetCode Solution image

Problem Statement of Check if All A’s Appears Before All B’s

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'.

See also  400. Nth Digit LeetCode Solution

Complexity Analysis

  • Time Complexity: O(n)
  • Space Complexity: O(n)

2124. Check if All A’s Appears Before All B’s LeetCode Solution in C++

class Solution {
 public:
  bool checkString(string s) {
    return s.find("ba") == string::npos;
  }
};
/* code provided by PROGIEZ */

2124. Check if All A’s Appears Before All B’s LeetCode Solution in Java

class Solution {
  public boolean checkString(String s) {
    return !s.contains("ba");
  }
}
// code provided by PROGIEZ

2124. Check if All A’s Appears Before All B’s LeetCode Solution in Python

class Solution:
  def checkString(self, s: str) -> bool:
    return 'ba' not in s
# code by PROGIEZ

Additional Resources

Happy Coding! Keep following PROGIEZ for more updates and solutions.