Open In App

Longest Span with same Sum in two Binary arrays

Last Updated : 05 Jun, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given two binary arrays, a1[] and a2[] of the same size n. Find the length of the longest common span (i, j) where j >= i such that 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

Input: a1[] = [0, 0, 1, 0]
a2[] = [1, 1, 1, 1]
Output: 1

[Naive Approach] Checking Each Subarray - O(n^2) 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.

C++
// C++ program to find Longest Span
// with same Sum in two Binary Arrays
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int longestCommonSum(vector<int> &a1, vector<int> &a2) {
    int n = a1.size();
    int res = 0;
    
    // Check all possible subarrays
    for (int i = 0; i < n; i++) {
        int sum1 = 0, sum2 = 0;
        
        for (int j = i; j < n; j++) {
            
            // Calculate sum for current subarray
            sum1 += a1[j];
            sum2 += a2[j];
            
            // If sums are equal, update result
            if (sum1 == sum2) {
                res = max(res, j - i + 1);
            }
        }
    }
    
    return res;
}

int main() {
    vector<int> a1 = {0, 1, 0, 0, 0, 0};
    vector<int> a2 = {1, 0, 1, 0, 0, 1};
    cout << longestCommonSum(a1, a2);
    return 0;
}
Java
// Java program to find Longest Span
// with same Sum in two Binary Arrays

class GfG {
    static int longestCommonSum(int[] a1, int[] a2) {
        int n = a1.length;
        int res = 0;
        
        // Check all possible subarrays
        for (int i = 0; i < n; i++) {
            int sum1 = 0, sum2 = 0;
            
            for (int j = i; j < n; j++) {
                
                // Calculate sum for current subarray
                sum1 += a1[j];
                sum2 += a2[j];
                
                // If sums are equal, update result
                if (sum1 == sum2) {
                    res = Math.max(res, j - i + 1);
                }
            }
        }
        
        return res;
    }

    public static void main(String[] args) {
        int[] a1 = {0, 1, 0, 0, 0, 0};
        int[] a2 = {1, 0, 1, 0, 0, 1};
        System.out.println(longestCommonSum(a1, a2));
    }
}
Python
# Python program to find Longest Span
# with same Sum in two Binary Arrays

def longestCommonSum(a1, a2):
    n = len(a1)
    res = 0
    
    # Check all possible subarrays
    for i in range(n):
        sum1 = 0
        sum2 = 0
        
        for j in range(i, n):
            
            # Calculate sum for current subarray
            sum1 += a1[j]
            sum2 += a2[j]
            
            # If sums are equal, update result
            if sum1 == sum2:
                res = max(res, j - i + 1)
    
    return res

if __name__ == "__main__":
    a1 = [0, 1, 0, 0, 0, 0]
    a2 = [1, 0, 1, 0, 0, 1]
    print(longestCommonSum(a1, a2))
C#
// C# program to find Longest Span
// with same Sum in two Binary Arrays

using System;

class GfG {
    static int longestCommonSum(int[] a1, int[] a2) {
        int n = a1.Length;
        int res = 0;
        
        // Check all possible subarrays
        for (int i = 0; i < n; i++) {
            int sum1 = 0, sum2 = 0;
            
            for (int j = i; j < n; j++) {
                
                // Calculate sum for current subarray
                sum1 += a1[j];
                sum2 += a2[j];
                
                // If sums are equal, update result
                if (sum1 == sum2) {
                    res = Math.Max(res, j - i + 1);
                }
            }
        }
        
        return res;
    }

    static void Main() {
        int[] a1 = {0, 1, 0, 0, 0, 0};
        int[] a2 = {1, 0, 1, 0, 0, 1};
        Console.WriteLine(longestCommonSum(a1, a2));
    }
}
JavaScript
// JavaScript program to find Longest Span
// with same Sum in two Binary Arrays

function longestCommonSum(a1, a2) {
    let n = a1.length;
    let res = 0;
    
    // Check all possible subarrays
    for (let i = 0; i < n; i++) {
        let sum1 = 0, sum2 = 0;
        
        for (let j = i; j < n; j++) {
            
            // Calculate sum for current subarray
            sum1 += a1[j];
            sum2 += a2[j];
            
            // If sums are equal, update result
            if (sum1 == sum2) {
                res = Math.max(res, j - i + 1);
            }
        }
    }
    
    return res;
}

let a1 = [0, 1, 0, 0, 0, 0];
let a2 = [1, 0, 1, 0, 0, 1];
console.log(longestCommonSum(a1, a2));

Output
4

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

The idea is to create a difference array to store the first occurrence of each possible difference value, then traverse both arrays while maintaining running sums and checking if the current difference has been seen before to find the longest span.

Step by step approach:

  1. Create a difference array of size 2n+1 initialized to -1 to handle negative differences.
  2. Traverse both arrays while maintaining running sums for each array:
    • Calculate current difference and add n to handle negative indices in the difference array.
    • If difference is zero, update result as current index + 1 (span from beginning).
    • If difference exists in array, calculate span length and update result, otherwise store current index.
C++
// C++ program to find Longest Span
// with same Sum in two Binary arrays
#include <bits/stdc++.h>
using namespace std;

int longestCommonSum(vector<int> &a1, vector<int> &a2) {
    int n = a1.size();
    int res = 0;
    
    // Create difference array 
    // to store first occurrence
    vector<int> diff(2 * n + 1, -1);
    
    int sum1 = 0, sum2 = 0;
    
    for (int i = 0; i < n; i++) {
        sum1 += a1[i];
        sum2 += a2[i];
        
        int currentDiff = sum1 - sum2;
        
        // Add n to handle negative differences
        int index = currentDiff + n;
        
        // If difference is 0, entire subarray 
        // from 0 to i has equal sum
        if (currentDiff == 0) {
            res = max(res, i + 1);
        }
        
        // If this difference has been seen before
        else if (diff[index] != -1) {
            res = max(res, i - diff[index]);
        } 
        else {
            
            // Store first occurrence of this difference
            diff[index] = i;
        }
    }
    
    return res;
}

int main() {
    vector<int> a1 = {0, 1, 0, 0, 0, 0};
    vector<int> a2 = {1, 0, 1, 0, 0, 1};
    cout << longestCommonSum(a1, a2);
    return 0;
}
Java
// Java program to find Longest Span
// with same Sum in two Binary arrays

class GfG {
    static int longestCommonSum(int[] a1, int[] a2) {
        int n = a1.length;
        int res = 0;
        
        // Create difference array 
        // to store first occurrence
        int[] diff = new int[2 * n + 1];
        for (int i = 0; i < diff.length; i++)
            diff[i] = -1;
        
        int sum1 = 0, sum2 = 0;
        
        for (int i = 0; i < n; i++) {
            sum1 += a1[i];
            sum2 += a2[i];
            
            int currentDiff = sum1 - sum2;
            
            // Add n to handle negative differences
            int index = currentDiff + n;
            
            // If difference is 0, entire subarray 
            // from 0 to i has equal sum
            if (currentDiff == 0) {
                res = Math.max(res, i + 1);
            }
            
            // If this difference has been seen before
            else if (diff[index] != -1) {
                res = Math.max(res, i - diff[index]);
            } 
            else {
                
                // Store first occurrence of this difference
                diff[index] = i;
            }
        }
        
        return res;
    }

    public static void main(String[] args) {
        int[] a1 = {0, 1, 0, 0, 0, 0};
        int[] a2 = {1, 0, 1, 0, 0, 1};
        System.out.println(longestCommonSum(a1, a2));
    }
}
Python
# Python program to find Longest Span
# with same Sum in two Binary arrays

def longestCommonSum(a1, a2):
    n = len(a1)
    res = 0
    
    # Create difference array 
    # to store first occurrence
    diff = [-1] * (2 * n + 1)
    
    sum1 = 0
    sum2 = 0
    
    for i in range(n):
        sum1 += a1[i]
        sum2 += a2[i]
        
        currentDiff = sum1 - sum2
        
        # Add n to handle negative differences
        index = currentDiff + n
        
        # If difference is 0, entire subarray 
        # from 0 to i has equal sum
        if currentDiff == 0:
            res = max(res, i + 1)
        
        # If this difference has been seen before
        elif diff[index] != -1:
            res = max(res, i - diff[index])
        else:
            
            # Store first occurrence of this difference
            diff[index] = i
    
    return res

if __name__ == "__main__":
    a1 = [0, 1, 0, 0, 0, 0]
    a2 = [1, 0, 1, 0, 0, 1]
    print(longestCommonSum(a1, a2))
C#
// C# program to find Longest Span
// with same Sum in two Binary arrays

using System;

class GfG {
    static int longestCommonSum(int[] a1, int[] a2) {
        int n = a1.Length;
        int res = 0;
        
        // Create difference array 
        // to store first occurrence
        int[] diff = new int[2 * n + 1];
        for (int i = 0; i < diff.Length; i++)
            diff[i] = -1;
        
        int sum1 = 0, sum2 = 0;
        
        for (int i = 0; i < n; i++) {
            sum1 += a1[i];
            sum2 += a2[i];
            
            int currentDiff = sum1 - sum2;
            
            // Add n to handle negative differences
            int index = currentDiff + n;
            
            // If difference is 0, entire subarray 
            // from 0 to i has equal sum
            if (currentDiff == 0) {
                res = Math.Max(res, i + 1);
            }
            
            // If this difference has been seen before
            else if (diff[index] != -1) {
                res = Math.Max(res, i - diff[index]);
            } 
            else {
                
                // Store first occurrence of this difference
                diff[index] = i;
            }
        }
        
        return res;
    }

    static void Main() {
        int[] a1 = {0, 1, 0, 0, 0, 0};
        int[] a2 = {1, 0, 1, 0, 0, 1};
        Console.WriteLine(longestCommonSum(a1, a2));
    }
}
JavaScript
// JavaScript program to find Longest Span
// with same Sum in two Binary arrays

function longestCommonSum(a1, a2) {
    let n = a1.length;
    let res = 0;
    
    // Create difference array 
    // to store first occurrence
    let diff = new Array(2 * n + 1).fill(-1);
    
    let sum1 = 0, sum2 = 0;
    
    for (let i = 0; i < n; i++) {
        sum1 += a1[i];
        sum2 += a2[i];
        
        let currentDiff = sum1 - sum2;
        
        // Add n to handle negative differences
        let index = currentDiff + n;
        
        // If difference is 0, entire subarray 
        // from 0 to i has equal sum
        if (currentDiff == 0) {
            res = Math.max(res, i + 1);
        }
        
        // If this difference has been seen before
        else if (diff[index] != -1) {
            res = Math.max(res, i - diff[index]);
        } 
        else {
            
            // Store first occurrence of this difference
            diff[index] = i;
        }
    }
    
    return res;
}

let a1 = [0, 1, 0, 0, 0, 0];
let a2 = [1, 0, 1, 0, 0, 1];
console.log(longestCommonSum(a1, a2));

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.

C++
// C++ program to find Longest Span
// with same Sum in two Binary arrays
#include <bits/stdc++.h>
using namespace std;

int longestCommonSum(vector<int> &a1, vector<int> &a2) {
    int n = a1.size();
    int res = 0;
    
    // Hash map to store first occurrence of each difference
    unordered_map<int, int> diffMap;
    
    int sum1 = 0, sum2 = 0;
    
    for (int i = 0; i < n; i++) {
        sum1 += a1[i];
        sum2 += a2[i];
        
        int currentDiff = sum1 - sum2;
        
        // If difference is 0, entire subarray 
        // from 0 to i has equal sum
        if (currentDiff == 0) {
            res = max(res, i + 1);
        }
        
        // If this difference has been seen before
        else if (diffMap.find(currentDiff) != diffMap.end()) {
            res = max(res, i - diffMap[currentDiff]);
        } 
        else {
            
            // Store first occurrence of this difference
            diffMap[currentDiff] = i;
        }
    }
    
    return res;
}

int main() {
    vector<int> a1 = {0, 1, 0, 0, 0, 0};
    vector<int> a2 = {1, 0, 1, 0, 0, 1};
    cout << longestCommonSum(a1, a2);
    return 0;
}
Java
// Java program to find Longest Span
// with same Sum in two Binary arrays

import java.util.HashMap;

class GfG {
    static int longestCommonSum(int[] a1, int[] a2) {
        int n = a1.length;
        int res = 0;
        
        // Hash map to store first occurrence of each difference
        HashMap<Integer, Integer> diffMap = new HashMap<>();
        
        int sum1 = 0, sum2 = 0;
        
        for (int i = 0; i < n; i++) {
            sum1 += a1[i];
            sum2 += a2[i];
            
            int currentDiff = sum1 - sum2;
            
            // If difference is 0, entire subarray 
            // from 0 to i has equal sum
            if (currentDiff == 0) {
                res = Math.max(res, i + 1);
            }
            
            // If this difference has been seen before
            else if (diffMap.containsKey(currentDiff)) {
                res = Math.max(res, i - diffMap.get(currentDiff));
            } 
            else {
                
                // Store first occurrence of this difference
                diffMap.put(currentDiff, i);
            }
        }
        
        return res;
    }

    public static void main(String[] args) {
        int[] a1 = {0, 1, 0, 0, 0, 0};
        int[] a2 = {1, 0, 1, 0, 0, 1};
        System.out.println(longestCommonSum(a1, a2));
    }
}
Python
# Python program to find Longest Span
# with same Sum in two Binary arrays

def longestCommonSum(a1, a2):
    n = len(a1)
    res = 0
    
    # Hash map to store first occurrence of each difference
    diffMap = {}
    
    sum1 = 0
    sum2 = 0
    
    for i in range(n):
        sum1 += a1[i]
        sum2 += a2[i]
        
        currentDiff = sum1 - sum2
        
        # If difference is 0, entire subarray 
        # from 0 to i has equal sum
        if currentDiff == 0:
            res = max(res, i + 1)
        
        # If this difference has been seen before
        elif currentDiff in diffMap:
            res = max(res, i - diffMap[currentDiff])
        else:
            
            # Store first occurrence of this difference
            diffMap[currentDiff] = i
    
    return res

if __name__ == "__main__":
    a1 = [0, 1, 0, 0, 0, 0]
    a2 = [1, 0, 1, 0, 0, 1]
    print(longestCommonSum(a1, a2))
C#
// C# program to find Longest Span
// with same Sum in two Binary arrays

using System;
using System.Collections.Generic;

class GfG {
    static int longestCommonSum(int[] a1, int[] a2) {
        int n = a1.Length;
        int res = 0;
        
        // Hash map to store first occurrence of each difference
        Dictionary<int, int> diffMap = new Dictionary<int, int>();
        
        int sum1 = 0, sum2 = 0;
        
        for (int i = 0; i < n; i++) {
            sum1 += a1[i];
            sum2 += a2[i];
            
            int currentDiff = sum1 - sum2;
            
            // If difference is 0, entire subarray 
            // from 0 to i has equal sum
            if (currentDiff == 0) {
                res = Math.Max(res, i + 1);
            }
            
            // If this difference has been seen before
            else if (diffMap.ContainsKey(currentDiff)) {
                res = Math.Max(res, i - diffMap[currentDiff]);
            } 
            else {
                
                // Store first occurrence of this difference
                diffMap[currentDiff] = i;
            }
        }
        
        return res;
    }

    static void Main() {
        int[] a1 = {0, 1, 0, 0, 0, 0};
        int[] a2 = {1, 0, 1, 0, 0, 1};
        Console.WriteLine(longestCommonSum(a1, a2));
    }
}
JavaScript
// JavaScript program to find Longest Span
// with same Sum in two Binary arrays

function longestCommonSum(a1, a2) {
    let n = a1.length;
    let res = 0;
    
    // Hash map to store first occurrence of each difference
    let diffMap = new Map();
    
    let sum1 = 0, sum2 = 0;
    
    for (let i = 0; i < n; i++) {
        sum1 += a1[i];
        sum2 += a2[i];
        
        let currentDiff = sum1 - sum2;
        
        // If difference is 0, entire subarray 
        // from 0 to i has equal sum
        if (currentDiff === 0) {
            res = Math.max(res, i + 1);
        }
        
        // If this difference has been seen before
        else if (diffMap.has(currentDiff)) {
            res = Math.max(res, i - diffMap.get(currentDiff));
        } 
        else {
            
            // Store first occurrence of this difference
            diffMap.set(currentDiff, i);
        }
    }
    
    return res;
}

let a1 = [0, 1, 0, 0, 0, 0];
let a2 = [1, 0, 1, 0, 0, 1];
console.log(longestCommonSum(a1, a2));

Output
4

Next Article
Practice Tags :

Similar Reads