Skip to main content
Back to problems
#525
Medium Algorithms

Contiguous array

Array Hash Table Prefix Sum
50.8% acceptance
Feb 19, 2026
8754
445
Given a binary array nums, return the maximum length of a contiguous subarray with an equal number of 0 and 1.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
use std::collections::HashMap;
impl Solution {
  pub fn find_max_length(nums: Vec<i32>) -> i32 {
    let mut map: HashMap<i32, i32> = HashMap::new();
    map.insert(0, -1);
    let mut count = 0i32;
    let mut result = 0i32;
    for (i, &n) in nums.iter().enumerate() {
      count += if n == 1 { 1 } else { -1 };
      if let Some(&prev) = map.get(&count) {
        result = result.max(i as i32 - prev);
      } else {
        map.insert(count, i as i32);
      }
    }
    result
  }
}