githubEdit

24. Longest Span in two Binary Arrays

βœ… GFG solution to Longest Span in two Binary Arrays: find longest span with equal sums using prefix difference and hash map technique. πŸš€

The problem can be found at the following link: πŸ”— Question Linkarrow-up-right

🧩 Problem Description

Given two binary arrays, a1[] and a2[] of equal length, find the length of longest common span (i, j), where i <= j such that:

a1[i] + a1[i+1] + ... + a1[j] = a2[i] + a2[i+1] + ... + 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 (0-based indexing).
Sum in a1[1:4] = 1+0+0+0 = 1, Sum in a2[1:4] = 0+1+0+0 = 1

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 (0-based indexing).

Example 3

πŸ”’ Constraints

  • $1 \le \text{a1.size()} = \text{a2.size()} \le 10^6$

  • $0 \le \text{a1}[i], \text{a2}[i] \le 1$

βœ… My Approach

The optimal solution uses Difference Array with Hash Map:

Prefix Difference Technique

  1. Key Transformation:

    • Instead of tracking two separate prefix sums, track their difference.

    • Let diff = prefixSum(a1) - prefixSum(a2).

    • If diff[i] == diff[j], then sum from i+1 to j is equal in both arrays.

  2. Hash Map Strategy:

    • Store first occurrence of each difference value.

    • Initialize with map[0] = -1 to handle spans starting from index 0.

    • For each position, calculate cumulative difference.

  3. Algorithm Steps:

    • Iterate through both arrays simultaneously.

    • Update running difference: diff += a1[i] - a2[i].

    • If this difference seen before, calculate span length: i - map[diff].

    • If not seen, store first occurrence: map[diff] = i.

  4. Return Result:

    • Maximum span length found during traversal.

Mathematical Insight: If prefixSum1[j] - prefixSum2[j] = prefixSum1[i] - prefixSum2[i], then sum(a1[i+1:j+1]) = sum(a2[i+1:j+1]).

πŸ“ Time and Auxiliary Space Complexity

  • Expected Time Complexity: O(n), where n is the length of the arrays. We make a single pass through both arrays, and each hash map operation (lookup and insert) takes O(1) average time.

  • Expected Auxiliary Space Complexity: O(n), as in the worst case, all cumulative differences could be unique, requiring O(n) space in the hash map to store all distinct difference values.

πŸ§‘β€πŸ’» Code (C++)

chevron-right⚑ View Alternative Approaches with Code and Analysishashtag

πŸ“Š 2️⃣ Separate Prefix Sum Arrays

πŸ’‘ Algorithm Steps:

  1. Maintain two separate prefix sum arrays for a1 and a2.

  2. Use hash map to store first occurrence of each difference.

  3. Calculate difference at each position and check for previous occurrences.

  4. Track maximum span length throughout the process.

πŸ“ Complexity Analysis:

  • Time: ⏱️ O(n) - Single pass with hash operations

  • Auxiliary Space: πŸ’Ύ O(n) - Hash map storage

βœ… Why This Approach?

  • Clear separation of prefix sum calculation

  • Explicit handling of zero difference case

  • More verbose but easier to understand

πŸ“Š 3️⃣ Difference Array Approach

πŸ’‘ Algorithm Steps:

  1. Create a difference array: diff[i] = a1[i] - a2[i].

  2. Find longest subarray in diff with sum = 0.

  3. Use hash map to track prefix sums of difference array.

  4. Apply same technique as longest subarray with sum K.

πŸ“ Complexity Analysis:

  • Time: ⏱️ O(n) - Linear pass with hash operations

  • Auxiliary Space: πŸ’Ύ O(n) - Difference array and hash map

βœ… Why This Approach?

  • Transforms problem to classic longest zero-sum subarray

  • Explicit difference array for clarity

  • Educational value in problem transformation

πŸ†š πŸ” Comparison of Approaches

πŸš€ Approach

⏱️ Time Complexity

πŸ’Ύ Space Complexity

βœ… Pros

⚠️ Cons

🎯 Prefix Difference

🟒 O(n)

🟑 O(n)

πŸš€ Optimal, single pass

πŸ’Ύ Hash map overhead

πŸ“Š Separate Prefix Sums

🟒 O(n)

🟑 O(n)

πŸ“– Clear logic flow

πŸ”§ More verbose

πŸ“ˆ Difference Array

🟒 O(n)

🟑 O(n)

πŸ” Problem transformation

πŸ’Ύ Extra array space

πŸ† Best Choice Recommendation

🎯 Scenario

πŸŽ–οΈ Recommended Approach

πŸ”₯ Performance Rating

πŸ… Optimal performance needed

πŸ₯‡ Prefix Difference

β˜…β˜…β˜…β˜…β˜…

πŸ“– Learning/Understanding

πŸ₯ˆ Separate Prefix Sums

β˜…β˜…β˜…β˜…β˜…

🎯 Educational purposes

πŸ₯‰ Difference Array

β˜…β˜…β˜…β˜…β˜†

β˜• Code (Java)

🐍 Code (Python)

🧠 Contribution and Support

For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: πŸ“¬ Any Questions?arrow-up-right. 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