
You are given two binary arrays, a1 and a2, of the same size N. A binary array is one that contains only 0s and 1s.
Your task is to find the length of the longest contiguous subarray (span) [i...j] where the sum of its elements in a1 is equal to the sum of its elements in a2.
The first line of input contains an integer 'N', the size of the arrays.
The second line contains 'N' space-separated integers (0s and 1s) for array a1.
The third line contains 'N' space-separated integers (0s and 1s) for array a2.
Print a single integer representing the length of the longest span with an equal sum.
If no such span exists, print 0.
The condition sum(a1[i...j]) == sum(a2[i...j]) can be rewritten as sum(a1[i...j]) - sum(a2[i...j]) == 0.
This is equivalent to sum(a1[k] - a2[k]) == 0 for k from i to j.
The problem can be transformed by creating a temporary difference array diff[k] = a1[k] - a2[k]. The problem is now to find the longest subarray in diff that sums to zero.
This subproblem can be solved efficiently in O(N) time using a hash map to store prefix sums.
6
0 1 0 0 0 0
1 0 1 0 0 1
4
1. Create the difference array: `diff = {-1, 1, -1, 0, 0, -1}`.
2. Find the longest subarray in `diff` that sums to 0.
3. The subarray from index 1 to 4 is `{1, -1, 0, 0}`, and its sum is 0.
4. The length of this subarray is `4 - 1 + 1 = 4`.
3
0 0 0
1 1 1
0
Difference array `diff = {-1, -1, -1}`. No subarray in this array sums to 0.
The expected time complexity is O(N).
1 <= N <= 10^5
`a1[i]` and `a2[i]` are either 0 or 1.
Time limit: 1 sec