diff[i] is "count of 1s" minus "count of 0s" so far.

For given i and j, if diff[i] == diff[j], then the subarray between i and j is a contiguous array as defined in the questions.

For any value of diff[], we save the index of the first item in the hashmap. Then once the value appears again, we get the length of the subarray between the current index and the index of the first item.

```
public int findMaxLength(int[] nums) {
int res = 0;
int n = nums.length;
int[] diff = new int[n + 1];
Map<Integer, Integer> map = new HashMap<>();
map.put(0, 0);
for (int i = 1; i <= n; i++) {
diff[i] = diff[i - 1] + (nums[i - 1] == 0 ? -1 : 1);
if (!map.containsKey(diff[i]))
map.put(diff[i], i);
else
res = Math.max(res, i - map.get(diff[i]));
}
return res;
}
```