Skip to main content
Back to problems
#2609
Easy Algorithms

Find the longest balanced substring of a binary string

String
46.4% acceptance
Feb 25, 2026
391
32
You are given a binary string s consisting only of zeroes and ones. A substring of s is considered balanced if all zeroes are before ones and the number of zeroes is equal to the number of ones inside the substring. Notice that the empty substring is considered a balanced substring. Return the length of the longest balanced substring of s. A substring is a contiguous sequence of characters within a string.

Solution

Rust
Time O(n²)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn find_the_longest_balanced_substring(s: String) -> i32 {
    let bytes = s.as_bytes();
    let n = bytes.len();
    let mut ans = 0;
    let mut i = 0;

    while i < n {
      // Count consecutive zeros
      let mut zeros = 0;
      while i < n && bytes[i] == b'0' {
        zeros += 1;
        i += 1;
      }
      // Count consecutive ones
      let mut ones = 0;
      while i < n && bytes[i] == b'1' {
        ones += 1;
        i += 1;
      }
      if zeros > 0 && ones > 0 {
        let balanced = 2 * zeros.min(ones);
        if balanced > ans {
          ans = balanced;
        }
      }
    }
    ans as i32
  }
}