DDSA Solutions

2609. Find the Longest Balanced Substring of a Binary String

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

Approach

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

Key Techniques

String

String problems range from simple character counting to complex pattern matching. Common approaches include two pointers, sliding window, prefix hashing, and the KMP algorithm. In C#, strings are immutable — use StringBuilder for efficient concatenation inside loops.

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?