Contiguous Array

medium array hash map prefix sum

Problem

Given a binary array nums, return the maximum length of a contiguous subarray with an equal number of 0s and 1s.

Inputnums = [0, 1, 0, 0, 1, 1, 0]
Output6
Indices [0..5] have three 0s and three 1s.

def find_max_length(nums):
    seen = {0: -1}
    s = 0
    best = 0
    for i, x in enumerate(nums):
        s += 1 if x == 1 else -1
        if s in seen:
            best = max(best, i - seen[s])
        else:
            seen[s] = i
    return best
function findMaxLength(nums) {
  const seen = new Map([[0, -1]]);
  let s = 0, best = 0;
  for (let i = 0; i < nums.length; i++) {
    s += nums[i] === 1 ? 1 : -1;
    if (seen.has(s)) {
      best = Math.max(best, i - seen.get(s));
    } else {
      seen.set(s, i);
    }
  }
  return best;
}
class Solution {
    public int findMaxLength(int[] nums) {
        Map<Integer, Integer> seen = new HashMap<>();
        seen.put(0, -1);
        int s = 0, best = 0;
        for (int i = 0; i < nums.length; i++) {
            s += nums[i] == 1 ? 1 : -1;
            if (seen.containsKey(s)) {
                best = Math.max(best, i - seen.get(s));
            } else {
                seen.put(s, i);
            }
        }
        return best;
    }
}
int findMaxLength(vector<int>& nums) {
    unordered_map<int, int> seen{{0, -1}};
    int s = 0, best = 0;
    for (int i = 0; i < (int)nums.size(); i++) {
        s += nums[i] == 1 ? 1 : -1;
        if (seen.count(s)) best = max(best, i - seen[s]);
        else seen[s] = i;
    }
    return best;
}
Time: O(n) Space: O(n)