Given two binary arrays, arr1[] and arr2[] of the same size n. Find the length of the longest common span (i, j) where j >= i such that arr1[i] + arr1[i+1] + …. + arr1[j] = arr2[i] + arr2[i+1] + …. + arr2[j]. The expected time complexity is Θ(n).
Examples:
Input: arr1[] = {0, 1, 0, 0, 0, 0};
arr2[] = {1, 0, 1, 0, 0, 1};
Output: 4
The longest span with same sum is from index 1 to 4.
Input: arr1[] = {0, 1, 0, 1, 1, 1, 1};
arr2[] = {1, 1, 1, 1, 1, 0, 1};
Output: 6
The longest span with same sum is from index 1 to 6.
Input: arr1[] = {0, 0, 0};
arr2[] = {1, 1, 1};
Output: 0
Input: arr1[] = {0, 0, 1, 0};
arr2[] = {1, 1, 1, 1};
Output: 1
Method 1 (Simple Solution) One by one by consider same subarrays of both arrays. For all subarrays, compute sums and if sums are same and current length is more than max length, then update max length. Below is C++ implementation of the simple approach.
C++
// A Simple C++ program to find longest common
// subarray of two binary arrays with same sum
#include<bits/stdc++.h>
usingnamespacestd;
// Returns length of the longest common subarray
// with same sum
intlongestCommonSum(boolarr1[], boolarr2[], intn)
{
// Initialize result
intmaxLen = 0;
// One by one pick all possible starting points
// of subarrays
for(inti=0; i<n; i++)
{
// Initialize sums of current subarrays
intsum1 = 0, sum2 = 0;
// Consider all points for starting with arr[i]
for(intj=i; j<n; j++)
{
// Update sums
sum1 += arr1[j];
sum2 += arr2[j];
// If sums are same and current length is
// more than maxLen, update maxLen
if(sum1 == sum2)
{
intlen = j-i+1;
if(len > maxLen)
maxLen = len;
}
}
}
returnmaxLen;
}
// Driver program to test above function
intmain()
{
boolarr1[] = {0, 1, 0, 1, 1, 1, 1};
boolarr2[] = {1, 1, 1, 1, 1, 0, 1};
intn = sizeof(arr1)/sizeof(arr1[0]);
cout << "Length of the longest common span with same "
"sum is "<< longestCommonSum(arr1, arr2, n);
return0;
}
Java
// A Simple Java program to find longest common
// subarray of two binary arrays with same sum
classTest
{
staticintarr1[] = newint[]{0, 1, 0, 1, 1, 1, 1};
staticintarr2[] = newint[]{1, 1, 1, 1, 1, 0, 1};
// Returns length of the longest common sum in arr1[]
// and arr2[]. Both are of same size n.
staticintlongestCommonSum(intn)
{
// Initialize result
intmaxLen = 0;
// One by one pick all possible starting points
// of subarrays
for(inti=0; i<n; i++)
{
// Initialize sums of current subarrays
intsum1 = 0, sum2 = 0;
// Consider all points for starting with arr[i]
for(intj=i; j<n; j++)
{
// Update sums
sum1 += arr1[j];
sum2 += arr2[j];
// If sums are same and current length is
// more than maxLen, update maxLen
if(sum1 == sum2)
{
intlen = j-i+1;
if(len > maxLen)
maxLen = len;
}
}
}
returnmaxLen;
}
// Driver method to test the above function
publicstaticvoidmain(String[] args)
{
System.out.print("Length of the longest common span with same sum is ");
print("Length of the longest common span with same "
"sum is",longestCommonSum(arr1, arr2, n))
# This code is contributed by
# Smitha Dinesh Semwal
C#
// A Simple C# program to find
// longest common subarray of
// two binary arrays with same sum
usingSystem;
classGFG
{
staticint[] arr1 = newint[]{0, 1, 0, 1, 1, 1, 1};
staticint[] arr2 = newint[]{1, 1, 1, 1, 1, 0, 1};
// Returns length of the longest
// common sum in arr1[] and arr2[].
// Both are of same size n.
staticintlongestCommonSum(intn)
{
// Initialize result
intmaxLen = 0;
// One by one pick all possible
// starting points of subarrays
for(inti = 0; i < n; i++)
{
// Initialize sums of current
// subarrays
intsum1 = 0, sum2 = 0;
// Consider all points for
// starting with arr[i]
for(intj = i; j < n; j++)
{
// Update sums
sum1 += arr1[j];
sum2 += arr2[j];
// If sums are same and current
// length is more than maxLen,
// update maxLen
if(sum1 == sum2)
{
intlen = j - i + 1;
if(len > maxLen)
maxLen = len;
}
}
}
returnmaxLen;
}
// Driver Code
publicstaticvoidMain()
{
Console.Write("Length of the longest "+
"common span with same sum is ");
Console.Write(longestCommonSum(arr1.Length));
}
}
// This code is contributed
// by ChitraNayal
PHP
<?php
// A Simple PHP program to find
// longest common subarray of
// two binary arrays with same sum
// Returns length of the longest
// common subarray with same sum
functionlongestCommonSum($arr1, $arr2, $n)
{
// Initialize result
$maxLen= 0;
// One by one pick all possible
// starting points of subarrays
for($i= 0; $i< $n; $i++)
{
// Initialize sums of
// current subarrays
$sum1= 0; $sum2= 0;
// Consider all points
// for starting with arr[i]
for($j= $i; $j< $n; $j++)
{
// Update sums
$sum1+= $arr1[$j];
$sum2+= $arr2[$j];
// If sums are same and current
// length is more than maxLen,
// update maxLen
if($sum1== $sum2)
{
$len= $j- $i+ 1;
if($len> $maxLen)
$maxLen= $len;
}
}
}
return$maxLen;
}
// Driver Code
$arr1= array(0, 1, 0, 1, 1, 1, 1);
$arr2= array(1, 1, 1, 1, 1, 0, 1);
$n= sizeof($arr1);
echo"Length of the longest common span ".
"with same ", "sum is ",
longestCommonSum($arr1, $arr2, $n);
// This code is contributed by aj_36
?>
Javascript
<script>
// A Simple Javascript program to find
// longest common subarray of
// two binary arrays with same sum
let arr1 = [0, 1, 0, 1, 1, 1, 1];
let arr2 = [1, 1, 1, 1, 1, 0, 1];
// Returns length of the longest
// common sum in arr1[] and arr2[].
// Both are of same size n.
functionlongestCommonSum(n)
{
// Initialize result
let maxLen = 0;
// One by one pick all possible
// starting points of subarrays
for(let i = 0; i < n; i++)
{
// Initialize sums of current
// subarrays
let sum1 = 0, sum2 = 0;
// Consider all points for
// starting with arr[i]
for(let j = i; j < n; j++)
{
// Update sums
sum1 += arr1[j];
sum2 += arr2[j];
// If sums are same and current
// length is more than maxLen,
// update maxLen
if(sum1 == sum2)
{
let len = j - i + 1;
if(len > maxLen)
maxLen = len;
}
}
}
returnmaxLen;
}
document.write("Length of the longest "+ "common span with same sum is ");
document.write(longestCommonSum(arr1.length));
</script>
Output :
Length of the longest common span with same sum is 6
Time Complexity : O(n2) Auxiliary Space : O(1)
Method 2 (Using Auxiliary Array) The idea is based on the below observations.
Since there are total n elements, maximum sum is n for both arrays.
The difference between two sums varies from -n to n. So there are total 2n + 1 possible values of difference.
If differences between prefix sums of two arrays become same at two points, then subarrays between these two points have same sum.
Below is the Complete Algorithm.
Create an auxiliary array of size 2n+1 to store starting points of all possible values of differences (Note that possible values of differences vary from -n to n, i.e., there are total 2n+1 possible values)
Initialize starting points of all differences as -1.
Initialize maxLen as 0 and prefix sums of both arrays as 0, preSum1 = 0, preSum2 = 0
Compute difference of current prefix sums: curr_diff = preSum1 – preSum2
Find index in diff array: diffIndex = n + curr_diff // curr_diff can be negative and can go till -n
If curr_diff is 0, then i+1 is maxLen so far
Else If curr_diff is seen first time, i.e., starting point of current diff is -1, then update starting point as i
Else (curr_diff is NOT seen first time), then consider i as ending point and find length of current same sum span. If this length is more, then update maxLen
Return maxLen
Below is the implementation of above algorithm.
C++
// A O(n) and O(n) extra space C++ program to find
// longest common subarray of two binary arrays with
// same sum
#include<bits/stdc++.h>
usingnamespacestd;
// Returns length of the longest common sum in arr1[]
// and arr2[]. Both are of same size n.
intlongestCommonSum(boolarr1[], boolarr2[], intn)
{
// Initialize result
intmaxLen = 0;
// Initialize prefix sums of two arrays
intpreSum1 = 0, preSum2 = 0;
// Create an array to store starting and ending
// indexes of all possible diff values. diff[i]
// would store starting and ending points for
// difference "i-n"
intdiff[2*n+1];
// Initialize all starting and ending values as -1.
memset(diff, -1, sizeof(diff));
// Traverse both arrays
for(inti=0; i<n; i++)
{
// Update prefix sums
preSum1 += arr1[i];
preSum2 += arr2[i];
// Compute current diff and index to be used
// in diff array. Note that diff can be negative
// and can have minimum value as -1.
intcurr_diff = preSum1 - preSum2;
intdiffIndex = n + curr_diff;
// If current diff is 0, then there are same number
// of 1's so far in both arrays, i.e., (i+1) is
// maximum length.
if(curr_diff == 0)
maxLen = i+1;
// If current diff is seen first time, then update
// starting index of diff.
elseif( diff[diffIndex] == -1)
diff[diffIndex] = i;
// Current diff is already seen
else
{
// Find length of this same sum common span
intlen = i - diff[diffIndex];
// Update max len if needed
if(len > maxLen)
maxLen = len;
}
}
returnmaxLen;
}
// Driver code
intmain()
{
boolarr1[] = {0, 1, 0, 1, 1, 1, 1};
boolarr2[] = {1, 1, 1, 1, 1, 0, 1};
intn = sizeof(arr1)/sizeof(arr1[0]);
cout << "Length of the longest common span with same "
"sum is "<< longestCommonSum(arr1, arr2, n);
return0;
}
Java
// A O(n) and O(n) extra space Java program to find
// longest common subarray of two binary arrays with
// same sum
classTest
{
staticintarr1[] = newint[]{0, 1, 0, 1, 1, 1, 1};
staticintarr2[] = newint[]{1, 1, 1, 1, 1, 0, 1};
// Returns length of the longest common sum in arr1[]
// and arr2[]. Both are of same size n.
staticintlongestCommonSum(intn)
{
// Initialize result
intmaxLen = 0;
// Initialize prefix sums of two arrays
intpreSum1 = 0, preSum2 = 0;
// Create an array to store starting and ending
// indexes of all possible diff values. diff[i]
// would store starting and ending points for
// difference "i-n"
intdiff[] = newint[2*n+1];
// Initialize all starting and ending values as -1.
for(inti = 0; i < diff.length; i++) {
diff[i] = -1;
}
// Traverse both arrays
for(inti=0; i<n; i++)
{
// Update prefix sums
preSum1 += arr1[i];
preSum2 += arr2[i];
// Compute current diff and index to be used
// in diff array. Note that diff can be negative
// and can have minimum value as -1.
intcurr_diff = preSum1 - preSum2;
intdiffIndex = n + curr_diff;
// If current diff is 0, then there are same number
// of 1's so far in both arrays, i.e., (i+1) is
// maximum length.
if(curr_diff == 0)
maxLen = i+1;
// If current diff is seen first time, then update
// starting index of diff.
elseif( diff[diffIndex] == -1)
diff[diffIndex] = i;
// Current diff is already seen
else
{
// Find length of this same sum common span
intlen = i - diff[diffIndex];
// Update max len if needed
if(len > maxLen)
maxLen = len;
}
}
returnmaxLen;
}
// Driver method to test the above function
publicstaticvoidmain(String[] args)
{
System.out.print("Length of the longest common span with same sum is ");
// This code is contributed by avanitrachhadiya2155
Javascript
<script>
// Javascript program to find largest subarray
// with equal number of 0's and 1's.
// Returns largest common subarray with equal
// number of 0s and 1s
functionlongestCommonSum(arr1,arr2,n)
{
// Find difference between the two
let arr = newArray(n);
for(let i = 0; i < n; i++)
arr[i] = arr1[i] - arr2[i];
// Creates an empty hashMap hM
let hM = newMap();
let sum = 0; // Initialize sum of elements
let max_len = 0; // Initialize result
// Traverse through the given array
for(let i = 0; i < n; i++)
{
// Add current element to sum
sum += arr[i];
// To handle sum=0 at last index
if(sum == 0)
max_len = i + 1;
// If this sum is seen before,
// then update max_len if required
if(hM.has(sum))
max_len = Math.max(max_len, i - hM.get(sum));
else// Else put this sum in hash table
hM.set(sum, i);
}
returnmax_len;
}
// Driver code
let arr1=[0, 1, 0, 1, 1, 1, 1];
let arr2=[1, 1, 1, 1, 1, 0, 1];
let n = arr1.length;
document.write(longestCommonSum(arr1, arr2, n));
// This code is contributed by ab2127
</script>
Output:
6
Time Complexity: O(n) (As the array is traversed only once.) Auxiliary Space: O(n) (As hashmap has been used which takes extra space.)
https://www.youtube.com/watch?v=xtfj4
-r_Ahs This article is contributed by Sumit Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy