07. Longest Span in two Binary Arrays
β GFG solution to find the longest span where two binary arrays have equal sum in the span. π
The problem can be found here: π Question Link
π§© Problem Description
Given two binary arrays a1[] and a2[] of the same size, find the length of the longest span (i, j) such that the sum of elements from a1[i] to a1[j] is equal to the sum of elements from a2[i] to a2[j].
π Examples
Example 1
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.
Example 2
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.
π Constraints
$1 \leq \text{a1.size()} = \text{a2.size()} \leq 10^6$
$a1[i], a2[i] \in {0,1}$
β
My Approach
Prefix Sum and Hash Map of Differences
π‘ Idea:
If the sums of a1 and a2 over some subarray are equal, then the difference of their prefix sums at two indices will be the same.
Detailed Explanation:
Calculate prefix sums for both arrays, but instead of storing separately, compute the difference of prefix sums
diff = prefixSum_a1 - prefixSum_a2.If at two different indices
iandjthe difference is the same, it means the subarray(i+1, j)has equal sums in both arrays.Track the first occurrence of each difference in a hash map.
When you encounter the same difference again, compute the span length and update the maximum span.
Special case: if difference is zero at index
i, update max span toi + 1.
This reduces the problem to finding the longest subarray with zero sum in the difference array.
βοΈ Algorithm Steps:
Initialize
maxLen = 0,sum1 = 0,sum2 = 0.Use a hash map
diffMapto store first occurrence of difference(sum1 - sum2).Traverse arrays from
i = 0ton-1:Update
sum1 += a1[i],sum2 += a2[i].Compute
diff = sum1 - sum2.If
diff == 0, updatemaxLen = i + 1.Else if
diffseen before at indexprevIndex, updatemaxLen = max(maxLen, i - prevIndex).Else store
diffwith current index indiffMap.
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(n), as we traverse arrays once and perform O(1) average lookups in the hash map.
Expected Auxiliary Space Complexity: O(n), for storing the hash map of prefix sum differences.
π§βπ» Code (C++)
π§βπ» Code (Java)
π Code (Python)
π§ Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: π¬ Any Questions?. Letβs make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated