2609. Find the Longest Balanced Substring of a Binary String
EasyView on LeetCode
Time: O(n)
Space: O(1)
Problem Overview
Find the Longest Balanced Substring of a Binary String (Easy) asks you to solve a structured algorithmic task. This is a common String pattern in coding interviews. Count consecutive zeros then ones per segment; take min of each pair and track max.
A full step-by-step explanation is being added. See the study guide for pattern-based practice.
Approach
Count consecutive zeros then ones per segment; take min of each pair and track max.
Related patterns: String
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;
}
}Was this solution helpful?