Skip to main content
Back to problems
#3713
Medium Algorithms

Longest balanced substring i

Hash Table String Counting Enumeration
69.7% acceptance
Feb 24, 2026
415
32
You are given a string s consisting of lowercase English letters. A substring of s is called balanced if all distinct characters in the substring appear the same number of times. Return the length of the longest balanced substring of s.

Solution

Rust
Time O(n²)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn longest_balanced(s: String) -> i32 {
    let s: Vec<u8> = s.bytes().collect();
    let n = s.len();
    let mut best = 0;
    for i in 0..n {
      let mut freq = [0u32; 26];
      for j in i..n {
        freq[(s[j] - b'a') as usize] += 1;
        let max_f = *freq.iter().max().unwrap();
        let min_f = freq.iter().filter(|&&c| c > 0).min().copied().unwrap();
        if max_f == min_f {
          best = best.max((j - i + 1) as i32);
        }
      }
    }
    best
  }
}