LeetCode 2124: Check if All A's Appears Before All B's Solution

Master LeetCode problem 2124 (Check if All A's Appears Before All B's), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

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

Easy

Problem Explanation

Explanation

To solve this problem, we can iterate through the characters of the string. Whenever we encounter a 'b' before an 'a', we return false. If we reach the end of the string without encountering this scenario, we return true.

  • Start iterating through the characters of the string.
  • If we encounter a 'b' before an 'a', return false.
  • If we reach the end of the string without encountering the above scenario, return true.

Time Complexity

The time complexity of this solution is O(n), where n is the length of the input string.

Space Complexity

The space complexity of this solution is O(1) as we are using constant extra space.

Solution Code

class Solution {
    public boolean checkIfAllAsBeforeBs(String s) {
        boolean foundB = false;
        
        for (char c : s.toCharArray()) {
            if (c == 'b' && !foundB) {
                foundB = true;
            } else if (c == 'a' && foundB) {
                return false;
            }
        }
        
        return true;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2124 (Check if All A's Appears Before All B's)?

This page provides optimized solutions for LeetCode problem 2124 (Check if All A's Appears Before All B's) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2124 (Check if All A's Appears Before All B's)?

The time complexity for LeetCode 2124 (Check if All A's Appears Before All B's) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2124 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2124 in Java, C++, or Python.

Back to LeetCode Solutions