Longest Span with same Sum in two Binary arrays
Last Updated :
05 Jun, 2025
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));
[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:
- Create a difference array of size 2n+1 initialized to -1 to handle negative differences.
- 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));
[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));
Similar Reads
Find k pairs with smallest sums in two arrays Given two integer arrays arr1[] and arr2[] sorted in ascending order and an integer k. Find k pairs with smallest sums such that one element of a pair belongs to arr1[] and other element belongs to arr2[] Examples: Input : arr1[] = {1, 7, 11} arr2[] = {2, 4, 6} k = 3Output : [1, 2], [1, 4], [1, 6]Ex
15+ min read
Find Sum of pair from two arrays with maximum sum Given two arrays of positive and distinct integers. The task is to find a pair from the two arrays with maximum sum. Note: The pair should contain one element from both the arrays. Examples: Input : arr1[] = {1, 2, 3}, arr2[] = {4, 5, 6} Output : Max Sum = 9 Pair (3, 6) has the maximum sum. Input :
6 min read
Longest common subarray in the given two arrays Given two arrays A[] and B[] of N and M integers respectively, the task is to find the maximum length of an equal subarray or the longest common subarray between the two given array. Examples: Input: A[] = {1, 2, 8, 2, 1}, B[] = {8, 2, 1, 4, 7} Output: 3 Explanation: The subarray that is common to b
15+ min read
Maximum length of subarray with same sum at corresponding indices from two Arrays Given two arrays A[] and B[] both consisting of N integers, the task is to find the maximum length of subarray [i, j] such that the sum of A[i... j] is equal to B[i... j]. Examples: Input: A[] = {1, 1, 0, 1}, B[] = {0, 1, 1, 0}Output: 3Explanation: For (i, j) = (0, 2), sum of A[0... 2] = sum of B[0.
6 min read
Maximum Sum Path in Two Arrays Given two sorted arrays having some elements in common. Find the sum of the maximum sum path to reach from the beginning of any array to the end of any of the two arrays. We can switch from one array to another array only at common elements. Note: The common elements do not have to be at the same in
14 min read
Minimum operations to make sum at least M from given two Arrays Given arrays A[] and B[] of size N and integer M, the task is to find out the minimum operations required to collect a sum of at least M by performing the following operations any number of times. Either choosing the first element of A[] or the first element of B[] remove that element from the front
11 min read
Find the longest Subarray with equal Sum and Product Given an array arr[] of N integers, the task is to find the length of the longest subarray where the sum of the elements in the subarray is equal to the product of the elements in the subarray. Examples: Input: arr[] = [1, 2, 1, 2, 2, 5, 6, 24]Output: 5Explanation: The subarray [1, 2, 1, 2, 2] has a
11 min read
Find all pairs with a given sum in two unsorted arrays Given two unsorted arrays of distinct elements, the task is to find all pairs from both arrays whose sum is equal to a given value X.Examples: Input: arr1[] = {-1, -2, 4, -6, 5, 7}, arr2[] = {6, 3, 4, 0} , x = 8Output: 4 4 5 3Input: arr1[] = {1, 2, 4, 5, 7}, arr2[] = {5, 6, 3, 4, 8}, x = 9Output: 1
13 min read
Maximum Prefix Sum possible by merging two given arrays Given two arrays A[] and B[] consisting of N and M integers respectively, the task is to calculate the maximum prefix sum that can be obtained by merging the two arrays. Examples: Input : A[] = {2, -1, 4, -5}, B[]={4, -3, 12, 4, -3}Output : 22Explanation: Merging the two arrays to generate the seque
11 min read
Maximum length sub-array which satisfies the given conditions Given a binary array arr[], the task is to find the length of the longest sub-array of the given array such that if the sub-array is divided into two equal-sized sub-arrays then both the sub-arrays either contain all 0s or all 1s. For example, the two sub-arrays must be of the form {0, 0, 0, 0} and
12 min read