VOOZH about

URL: https://www.geeksforgeeks.org/dsa/longest-span-sum-two-binary-arrays/

⇱ Longest Span with same Sum in two Binary arrays - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Longest Span with same Sum in two Binary arrays

Last Updated : 17 Jul, 2025

Given two binary arrays a1[] and a2[] of equal length, find the maximum length of a subarray [i...j] such that the sum of elements from i to j in both arrays is equal, i.e.,
a1[i] + a1[i+1] + ... + a1[j] == a2[i] + a2[i+1] + ... + a2[j].

Examples:

Input: a1[] = [0, 1, 0, 0, 0, 0], a2[] = [1, 0, 1, 0, 0, 1]
Output: 4
Explanation: The longest span with same sum is from index 1 to 4.

Input: a1[] = [0, 1, 0, 1, 1, 1, 1], a2[] = [1, 1, 1, 1, 1, 0, 1]
Output: 6
Explanation: The longest span with same sum is from index 1 to 6.

Input: a1[] = [0, 0, 0], a2[] = [1, 1, 1]
Output: 0
Explanation: There is no span where the sum of the elements in a1[] and a2[] is equal.

[Naive Approach] Checking Each Subarray - O(n2) Time and O(1) Space

The idea is to check all possible subarrays by considering every starting and ending position, calculate the sum for both arrays in each subarray, and keep track of the maximum length where sums are equal.


Output
4

[Expected Approach] Using Difference Array - O(n) Time and O(n) Space

If the sum of elements from index 0 to i in both arrays is the same at some earlier index and again at a later index, then the difference in sums between the arrays in that span must be zero.

Mathematical Proof:

  • Let prefixSum1[i] be the prefix sum of a1 from index 0 to i, prefixSum2[i] be the prefix sum of a2 from index 0 to i and diff = prefixSum1[i] - prefixSum2[i]
  • If the same diff is seen again at some earlier index j, then:
    prefixSum1[i]−prefixSum1[j] = prefixSum2[i]−prefixSum2[j],
    also, prefixSum1[j] - prefixSum2[j] = prefixSum1[i] - prefixSum2[i]
  • This implies the subarrays a1[j+1 ... i] and a2[j+1 ... i] have equal sums.

Step by Step Approach:

  • Create a difference array of size 2 * n + 1 and initialize all elements to -1.
  • Traverse both arrays while maintaining prefix sums prefixSum1and prefixSum2.
  • At each index i, compute the current difference: diff = prefixSum1 - prefixSum2.
  • Shift the difference by adding n to handle negative indices: diff += n.
  • If diff == n, the sums are equal from index 0 to i, so update maxLen as i + 1.
  • If the difference has been seen before, calculate the span: i - diffArray[diff] and update maxLen if it's larger.
  • If the difference is seen for the first time, store the current index at diffArray[diff].

Output
4

[Alternative Approach] Using Hash Map - O(n) Time and O(n) Space

The idea is to use a hash map to store the first occurrence of each difference value between cumulative sums, allowing us to handle both positive and negative differences efficiently.



Output
4
Comment