Last Updated: 19 Sep, 2025

Longest Span with Same Sum

Moderate
Asked in company
Amazon

Problem statement

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.


Input Format:
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.


Output Format:
Print a single integer representing the length of the longest span with an equal sum.

If no such span exists, print 0.


Note:
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.