Contiguous Array

Contiguous Array

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

LeetCode Problem - 252

import java.util.HashMap;
import java.util.Map;

class Solution {
    // Method to find the maximum length of a contiguous subarray with equal number of 0s and 1s
    public int findMaxLength(int[] nums) {
        // Convert 0s to -1s to simplify the problem
        for(int i = 0; i < nums.length; i++){
            if(nums[i] == 0) nums[i] = -1;
        }

        // Create a map to store the running sum and its corresponding index
        Map<Integer, Integer> hm = new HashMap<>();

        int maxLen = 0; // Initialize the maximum length of subarray
        int sum = 0; // Initialize the running sum
        for (int i = 0; i < nums.length; i++){ 
            sum += nums[i]; // Update the running sum
            // If the running sum becomes 0, update maxLen to include the current subarray
            if (sum == 0){
                maxLen = Math.max(maxLen, (i + 1));
            }

            // If the running sum is encountered before, update maxLen accordingly
            if (hm.containsKey(sum)){
                maxLen = Math.max(maxLen, i - hm.get(sum));
            } else {
                // Otherwise, put the current sum and its index into the map
                hm.put(sum, i);
            }
        }

        // Return the maximum length of the subarray
        return maxLen;
    }
}