Skip to main content
Back to problems
#3719
Medium Algorithms

Longest balanced subarray i

Array Hash Table Divide and Conquer Segment Tree Prefix Sum
65.7% acceptance
Feb 24, 2026
479
41
You are given an integer array nums. A subarray is called balanced if the number of distinct even numbers in the subarray is equal to the number of distinct odd numbers. Return the length of the longest balanced subarray.

Solution

Rust
Time O(n²)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn longest_balanced(nums: Vec<i32>) -> i32 {
    let n = nums.len();
    let mut best = 0;
    for i in 0..n {
      let mut evens = std::collections::HashSet::new();
      let mut odds = std::collections::HashSet::new();
      for j in i..n {
        if nums[j] % 2 == 0 { evens.insert(nums[j]); } else { odds.insert(nums[j]); }
        if evens.len() == odds.len() {
          best = best.max((j - i + 1) as i32);
        }
      }
    }
    best
  }
}