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:

    1. Calculate prefix sums for both arrays, but instead of storing separately, compute the difference of prefix sums diff = prefixSum_a1 - prefixSum_a2.

    2. If at two different indices i and j the difference is the same, it means the subarray (i+1, j) has equal sums in both arrays.

    3. Track the first occurrence of each difference in a hash map.

    4. When you encounter the same difference again, compute the span length and update the maximum span.

    5. Special case: if difference is zero at index i, update max span to i + 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 diffMap to store first occurrence of difference (sum1 - sum2).

  • Traverse arrays from i = 0 to n-1:

    • Update sum1 += a1[i], sum2 += a2[i].

    • Compute diff = sum1 - sum2.

    • If diff == 0, update maxLen = i + 1.

    • Else if diff seen before at index prevIndex, update maxLen = max(maxLen, i - prevIndex).

    • Else store diff with current index in diffMap.

πŸ“ 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++)

⚑ View Alternative Approaches with Code and Analysis

πŸ“Š 2️⃣ Difference Array + Zero-Sum Subarray

Transform the problem into finding the longest subarray with sum 0 using a difference array.

πŸ’‘ Algorithm Steps:

  1. Construct a new array diff[i] = arr1[i] - arr2[i].

  2. Find the longest subarray in diff whose sum is zero:

    • Use a prefix_sum and store the first index where each sum appears in a hash map.

    • If at any point, prefix_sum == 0, update result to i + 1.

    • If prefix_sum seen before, res = max(res, i - first_index[prefix_sum]).

πŸ“Œ Key Insight:

If two prefix sums at indices i and j are the same, then subarray sum between (i, j] is 0. This trick works beautifully for difference arrays!

πŸ“ Complexity Analysis:

  • Time: ⏱️ O(n)

  • Auxiliary Space: πŸ’Ύ O(n) β€” to store first index of each prefix sum.

βœ… Why This Approach?

  • Transforms the original problem into a classic subarray sum problem.

  • More readable than prefix diff directly on sums.

  • Leverages prefix tricks for optimal performance.

πŸ†š πŸ” Comparison of Approaches

πŸš€ Approach

⏱️ Time

πŸ’Ύ Space

βœ… Pros

⚠️ Cons

πŸ”„ Prefix Sum + HashMap

🟒 O(n)

🟒 O(n)

Most intuitive and efficient

β€”

βœ‚οΈ Diff Array + Zero-Sum Subarray

🟒 O(n)

🟑 O(n)

Turns into classic zero-sum problem

Slight extra preprocessing

πŸ† Best Choice by Scenario

🎯 Scenario

πŸ₯‡ Recommended Approach

🧠 Want clarity and optimal performance

πŸ₯‡ Prefix Sum + HashMap

♻️ Familiar with zero-sum tricks

πŸ₯ˆ Diff Array + Zero-Sum Subarray

πŸ§‘β€πŸ’» 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

Visitor counter

Last updated