DDSA
Advertisement

2609. Find the Longest Balanced Substring of a Binary String

Time: O(n)
Space: O(1)

Approach

Count consecutive zeros then ones per segment; take min of each pair and track max.

2609.cs
C#
// Approach: Count consecutive zeros then ones per segment; take min of each pair and track max.
// Time: O(n) Space: O(1)

public class Solution
{
    public int FindTheLongestBalancedSubstring(string s)
    {
        int ans = 0;
        int zeros = 0;
        int ones = 0;

        foreach (char c in s)
        {
            if (c == '0')
            {
                zeros = ones > 0 ? 1 : zeros + 1;
                ones = 0;
            }
            else
                ones++;

            if (zeros >= ones)
                ans = Math.Max(ans, ones);
        }

        return ans * 2;
    }
}
Advertisement
Was this solution helpful?