LeetCode 2609: Find the Longest Balanced Substring of a Binary String Solution

Master LeetCode problem 2609 (Find the Longest Balanced Substring of a Binary String), 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.

2609. Find the Longest Balanced Substring of a Binary String

Easy

Problem Explanation

Explanation

To find the longest balanced substring of a binary string, we can use a simple approach where we iterate through the string and keep track of the count of zeros and ones encountered so far. Whenever the count of zeros equals the count of ones, we update the length of the longest balanced substring found so far. We reset the counts whenever the counts become unequal or when we encounter a '1' before a '0'. Finally, we return the length of the longest balanced substring.

  • Initialize variables maxLen for storing the length of the longest balanced substring and zeros and ones counts to 0.
  • Iterate through the binary string:
    • If the current character is '0', increment the zeros count.
    • If the current character is '1', increment the ones count.
    • If zeros equals ones, update maxLen if the current balanced substring is longer.
    • Reset zeros and ones counts if the counts become unequal or if '1' is encountered before '0'.
  • Return the maxLen.

Time Complexity: O(N), where N is the length of the input string. Space Complexity: O(1)

Solution Code

public int longestBalancedSubstring(String s) {
    int maxLen = 0;
    int zeros = 0, ones = 0;
    
    for (char c : s.toCharArray()) {
        if (c == '0') {
            zeros++;
        } else {
            ones++;
        }
        
        if (zeros == ones) {
            maxLen = Math.max(maxLen, 2 * ones);
        } else if (ones > zeros) {
            zeros = 0;
            ones = 0;
        }
    }
    
    return maxLen;
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2609 (Find the Longest Balanced Substring of a Binary String)?

This page provides optimized solutions for LeetCode problem 2609 (Find the Longest Balanced Substring of a Binary String) 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 2609 (Find the Longest Balanced Substring of a Binary String)?

The time complexity for LeetCode 2609 (Find the Longest Balanced Substring of a Binary String) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2609 on DevExCode?

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

Back to LeetCode Solutions