Longest Span with same Sum in two Binary arrays
Given two binary arrays, a[] and b[] of the same size n. Find the length of the longest common span (i, j) where j >= i such that a[i] + a[i+1] + …. + a[j] = b[i] + b[i+1] + …. + b[j].
Examples:
Input: a[] = {0, 1, 0, 0, 0, 0}
b[] = {1, 0, 1, 0, 0, 1}
Output: 4
The longest span with same sum is from index 1 to 4.Input: a[] = {0, 1, 0, 1, 1, 1, 1}
b[] = {1, 1, 1, 1, 1, 0, 1}
Output: 6
The longest span with same sum is from index 1 to 6.
Input: a[] = {0, 0, 0}
b[] = {1, 1, 1}
Output: 0
Input: a[] = {0, 0, 1, 0}
b[] = {1, 1, 1, 1}
Output: 1
Naive Approach – O(n^2) Time and O(1) Space
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.
// A Simple C++ program to find longest common
// subarray of two binary arrays with same sum
#include<bits/stdc++.h>
using namespace std;
// Returns length of the longest common subarray
// with same sum
int longestCommonSum(vector<bool>& a, vector<bool>& b) {
int res = 0;
// One by one pick all possible starting points
// of subarrays
int n = a.size();
for (int i = 0; i < n; i++) {
// Initialize sums of current subarrays
int sum1 = 0, sum2 = 0;
// Consider all ending points starting with a[i]
for (int j = i; j < n; j++) {
sum1 += a[j];
sum2 += b[j];
// If sums are the same and current length
// is more than res, update res
if (sum1 == sum2) {
res = max(res, j - i + 1);
}
}
}
return res;
}
int main() {
vector<bool> a = {0, 1, 0, 1, 1, 1, 1};
vector<bool> b = {1, 1, 1, 1, 1, 0, 1};
cout << longestCommonSum(a, b);
return 0;
}
// A Simple Java program to find longest common
// subarray of two binary arrays with same sum
class Test
{
static int a[] = new int[]{0, 1, 0, 1, 1, 1, 1};
static int b[] = new int[]{1, 1, 1, 1, 1, 0, 1};
// Returns length of the longest common sum in a[]
// and b[]. Both are of same size n.
static int longestCommonSum(int n)
{
// Initialize result
int maxLen = 0;
// One by one pick all possible starting points
// of subarrays
for (int i=0; i<n; i++)
{
// Initialize sums of current subarrays
int sum1 = 0, sum2 = 0;
// Consider all points for starting with arr[i]
for (int j=i; j<n; j++)
{
// Update sums
sum1 += a[j];
sum2 += b[j];
// If sums are same and current length is
// more than maxLen, update maxLen
if (sum1 == sum2)
{
int len = j-i+1;
if (len > maxLen)
maxLen = len;
}
}
}
return maxLen;
}
// Driver method to test the above function
public static void main(String[] args)
{
System.out.print("Length of the longest common span with same sum is ");
System.out.println(longestCommonSum(a.length));
}
}
# A Simple python program to find longest common
# subarray of two binary arrays with same sum
# Returns length of the longest common subarray
# with same sum
def longestCommonSum(a, b, n):
# Initialize result
maxLen = 0
# One by one pick all possible starting points
# of subarrays
for i in range(0,n):
# Initialize sums of current subarrays
sum1 = 0
sum2 = 0
# Consider all points for starting with arr[i]
for j in range(i,n):
# Update sums
sum1 += a[j]
sum2 += b[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 program to test above function
a = [0, 1, 0, 1, 1, 1, 1]
b = [1, 1, 1, 1, 1, 0, 1]
n = len(a)
print("Length of the longest common span with same "
"sum is",longestCommonSum(a, b, n))
# This code is contributed by
# Smitha Dinesh Semwal
// A Simple C# program to find
// longest common subarray of
// two binary arrays with same sum
using System;
class GFG
{
static int[] a = new int[]{0, 1, 0, 1, 1, 1, 1};
static int[] b = new int[]{1, 1, 1, 1, 1, 0, 1};
// Returns length of the longest
// common sum in a[] and b[].
// Both are of same size n.
static int longestCommonSum(int n)
{
// Initialize result
int maxLen = 0;
// One by one pick all possible
// starting points of subarrays
for (int i = 0; i < n; i++)
{
// Initialize sums of current
// subarrays
int sum1 = 0, sum2 = 0;
// Consider all points for
// starting with arr[i]
for (int j = i; j < n; j++)
{
// Update sums
sum1 += a[j];
sum2 += b[j];
// If sums are same and current
// length is more than maxLen,
// update maxLen
if (sum1 == sum2)
{
int len = j - i + 1;
if (len > maxLen)
maxLen = len;
}
}
}
return maxLen;
}
// Driver Code
public static void Main()
{
Console.Write("Length of the longest " +
"common span with same sum is ");
Console.Write(longestCommonSum(a.Length));
}
}
// This code is contributed
// by ChitraNayal
<script>
// A Simple Javascript program to find
// longest common subarray of
// two binary arrays with same sum
let a = [0, 1, 0, 1, 1, 1, 1];
let b = [1, 1, 1, 1, 1, 0, 1];
// Returns length of the longest
// common sum in a[] and b[].
// Both are of same size n.
function longestCommonSum(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 += a[j];
sum2 += b[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;
}
}
}
return maxLen;
}
document.write("Length of the longest " + "common span with same sum is ");
document.write(longestCommonSum(a.length));
</script>
<?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
function longestCommonSum($a, $b, $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 += $a[$j];
$sum2 += $b[$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
$a = array(0, 1, 0, 1, 1, 1, 1);
$b = array (1, 1, 1, 1, 1, 0, 1);
$n = sizeof($a);
echo "Length of the longest common span ".
"with same ", "sum is ",
longestCommonSum($a, $b, $n);
// This code is contributed by aj_36
?>
Output
6
Expected Approach 1 – O(n) Time and O(n) Space
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 implementation of above algorithm.
// 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>
using namespace std;
// Returns length of the longest common sum in a[]
// and b[]. Both are of same size n.
int longestCommonSum(vector<bool>& a, vector<bool>& b) {
int res = 0;
// Prefix sums of two arrays
int preSum1 = 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"
int n = a.size();
vector<int> diff(2 * n + 1, -1);
// Traverse both arrays
for (int i = 0; i < n; i++) {
// Update prefix sums
preSum1 += a[i];
preSum2 += b[i];
// Compute current diff and index to be used
// in diff array. Note that diff can be negative
// and can have minimum value as -n.
int curr_diff = preSum1 - preSum2;
int diffIndex = n + curr_diff;
// If current diff is 0, then there are same number
// of 1's and 0's so far in both arrays, i.e., (i+1) is
// maximum length.
if (curr_diff == 0)
res = i + 1;
// If current diff is seen first time, update
// starting index of diff.
else if (diff[diffIndex] == -1)
diff[diffIndex] = i;
// Current diff is already seen which means
// there lies curr_diff = 0 in between
else {
// Find length of this same sum by
// calculating the common span and
// update result if required
res = max(res, i - diff[diffIndex]);
}
}
return res;
}
// Driver code
int main() {
vector<bool> a = {0, 1, 0, 1, 1, 1, 1};
vector<bool> b = {1, 1, 1, 1, 1, 0, 1};
cout << longestCommonSum(a, b);
return 0;
}
// A O(n) and O(n) extra space Java program to find
// longest common subarray of two binary arrays with
// same sum
class Test
{
static int a[] = new int[]{0, 1, 0, 1, 1, 1, 1};
static int b[] = new int[]{1, 1, 1, 1, 1, 0, 1};
// Returns length of the longest common sum in a[]
// and b[]. Both are of same size n.
static int longestCommonSum(int n)
{
// Initialize result
int maxLen = 0;
// Initialize prefix sums of two arrays
int preSum1 = 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"
int diff[] = new int[2*n+1];
// Initialize all starting and ending values as -1.
for (int i = 0; i < diff.length; i++) {
diff[i] = -1;
}
// Traverse both arrays
for (int i=0; i<n; i++)
{
// Update prefix sums
preSum1 += a[i];
preSum2 += b[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.
int curr_diff = preSum1 - preSum2;
int diffIndex = 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.
else if ( diff[diffIndex] == -1)
diff[diffIndex] = i;
// Current diff is already seen
else
{
// Find length of this same sum common span
int len = i - diff[diffIndex];
// Update max len if needed
if (len > maxLen)
maxLen = len;
}
}
return maxLen;
}
// Driver method to test the above function
public static void main(String[] args)
{
System.out.print("Length of the longest common span with same sum is ");
System.out.println(longestCommonSum(a.length));
}
}
# Python program to find longest common
# subarray of two binary arrays with
# same sum
def longestCommonSum(a, b, n):
# Initialize result
maxLen = 0
# Initialize prefix sums of two arrays
presum1 = presum2 = 0
# Create a dictionary to store indices
# of all possible sums
diff = {}
# Traverse both arrays
for i in range(n):
# Update prefix sums
presum1 += a[i]
presum2 += b[i]
# Compute current diff which will be
# used as index in diff dictionary
curr_diff = presum1 - presum2
# 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
elif curr_diff not in diff:
# save the index for this diff
diff[curr_diff] = i
else:
# calculate the span length
length = i - diff[curr_diff]
maxLen = max(maxLen, length)
return maxLen
# Driver program
a = [0, 1, 0, 1, 1, 1, 1]
b = [1, 1, 1, 1, 1, 0, 1]
print("Length of the longest common",
" span with same", end = " ")
print("sum is",longestCommonSum(a,
b, len(a)))
# This code is contributed by Abhijeet Nautiyal
// A O(n) and O(n) extra space C# program
// to find longest common subarray of two
// binary arrays with same sum
using System;
class GFG
{
static int[] a = new int[]{0, 1, 0, 1, 1, 1, 1};
static int[] b = new int[]{1, 1, 1, 1, 1, 0, 1};
// Returns length of the longest
// common sum in a[] and b[].
// Both are of same size n.
static int longestCommonSum(int n)
{
// Initialize result
int maxLen = 0;
// Initialize prefix sums of
// two arrays
int preSum1 = 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"
int[] diff = new int[2 * n + 1];
// Initialize all starting and ending
// values as -1.
for (int i = 0; i < diff.Length; i++)
{
diff[i] = -1;
}
// Traverse both arrays
for (int i = 0; i < n; i++)
{
// Update prefix sums
preSum1 += a[i];
preSum2 += b[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.
int curr_diff = preSum1 - preSum2;
int diffIndex = 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.
else if ( diff[diffIndex] == -1)
diff[diffIndex] = i;
// Current diff is already seen
else
{
// Find length of this same
// sum common span
int len = i - diff[diffIndex];
// Update max len if needed
if (len > maxLen)
maxLen = len;
}
}
return maxLen;
}
// Driver Code
public static void Main()
{
Console.Write("Length of the longest common " +
"span with same sum is ");
Console.WriteLine(longestCommonSum(a.Length));
}
}
// This code is contributed
// by Akanksha Rai(Abby_akku)
<script>
// A O(n) and O(n) extra space
// Javascript program to find longest
// common subarray of two binary arrays
// with same sum
let a = [0, 1, 0, 1, 1, 1, 1];
let b = [1, 1, 1, 1, 1, 0, 1];
// Returns length of the longest
// common sum in a[] and b[].
// Both are of same size n.
function longestCommonSum(n)
{
// Initialize result
let maxLen = 0;
// Initialize prefix sums of
// two arrays
let preSum1 = 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"
let diff = new Array(2 * n + 1);
// Initialize all starting and ending
// values as -1.
for (let i = 0; i < diff.length; i++)
{
diff[i] = -1;
}
// Traverse both arrays
for (let i = 0; i < n; i++)
{
// Update prefix sums
preSum1 += a[i];
preSum2 += b[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.
let curr_diff = preSum1 - preSum2;
let diffIndex = 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.
else if ( diff[diffIndex] == -1)
diff[diffIndex] = i;
// Current diff is already seen
else
{
// Find length of this same
// sum common span
let len = i - diff[diffIndex];
// Update max len if needed
if (len > maxLen)
maxLen = len;
}
}
return maxLen;
}
document.write("Length of the longest common "
+ "span with same sum is ");
document.write(longestCommonSum(a.length));
</script>
Output
6
Expected Approach 2 – Prefix Sum and Hashing – O(n) Time and O(n) Space
- Find difference array arr[] such that arr[i] = a[i] – b[i].
- Largest subarray with equal number of 0s and 1s in the difference array.
// C++ program to find largest subarray
// with equal number of 0's and 1's.
#include <bits/stdc++.h>
using namespace std;
// Returns largest common subarray with equal
// number of 0s and 1s in both a and b.
int longestCommonSum(vector<bool>& a, vector<bool>& b) {
// Find difference between the two
int n = a.size();
vector<int> arr(n);
for (int i = 0; i < n; i++)
arr[i] = a[i] - b[i];
// Creates an empty hashMap m
unordered_map<int, int> m;
int sum = 0; // Initialize sum of elements
int max_len = 0; // Initialize result
// Traverse through the given array
for (int i = 0; i < n; i++) {
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 (m.find(sum) != m.end())
max_len = max(max_len, i - m[sum]);
else
m[sum] = i;
}
return max_len;
}
int main() {
vector<bool> a = {0, 1, 0, 1, 1, 1, 1};
vector<bool> b = {1, 1, 1, 1, 1, 0, 1};
cout << longestCommonSum(a, b);
return 0;
}
// Java program to find largest subarray
// with equal number of 0's and 1's.
import java.io.*;
import java.util.*;
class GFG
{
// Returns largest common subarray with equal
// number of 0s and 1s
static int longestCommonSum(int[] a, int[] b, int n)
{
// Find difference between the two
int[] arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = a[i] - b[i];
// Creates an empty hashMap hM
HashMap<Integer, Integer> hM = new HashMap<>();
int sum = 0; // Initialize sum of elements
int max_len = 0; // Initialize result
// Traverse through the given array
for (int 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.containsKey(sum))
max_len = Math.max(max_len, i - hM.get(sum));
else // Else put this sum in hash table
hM.put(sum, i);
}
return max_len;
}
// Driver code
public static void main(String args[])
{
int[] a = {0, 1, 0, 1, 1, 1, 1};
int[] b = {1, 1, 1, 1, 1, 0, 1};
int n = a.length;
System.out.println(longestCommonSum(a, b, n));
}
}
// This code is contributed by rachana soma
# Python 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
def longestCommonSum(a, b, n):
# Find difference between the two
arr = [0 for i in range(n)]
for i in range(n):
arr[i] = a[i] - b[i];
# Creates an empty hashMap hM
hm = {}
sum = 0 # Initialize sum of elements
max_len = 0 #Initialize result
# Traverse through the given array
for i in range(n):
# 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 sum in hm:
max_len = max(max_len, i - hm[sum])
else: # Else put this sum in hash table
hm[sum] = i
return max_len
# Driver code
a = [0, 1, 0, 1, 1, 1, 1]
b = [1, 1, 1, 1, 1, 0, 1]
n = len(a)
print(longestCommonSum(a, b, n))
# This code is contributed by rag2127
// C# program to find largest subarray
// with equal number of 0's and 1's.
using System;
using System.Collections.Generic;
public class GFG
{
// Returns largest common subarray with equal
// number of 0s and 1s
static int longestCommonSum(int[] a, int[] b, int n)
{
// Find difference between the two
int[] arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = a[i] - b[i];
// Creates an empty hashMap hM
Dictionary<int,int> hM = new Dictionary<int,int>();
int sum = 0; // Initialize sum of elements
int max_len = 0; // Initialize result
// Traverse through the given array
for (int 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.ContainsKey(sum))
max_len = Math.Max(max_len, i - hM[sum]);
else // Else put this sum in hash table
hM[sum] = i;
}
return max_len;
}
// Driver code
static public void Main ()
{
int[] a = {0, 1, 0, 1, 1, 1, 1};
int[] b = {1, 1, 1, 1, 1, 0, 1};
int n = a.Length;
Console.WriteLine(longestCommonSum(a, b, n));
}
}
// This code is contributed by avanitrachhadiya2155
<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
function longestCommonSum(a,b,n)
{
// Find difference between the two
let arr = new Array(n);
for (let i = 0; i < n; i++)
arr[i] = a[i] - b[i];
// Creates an empty hashMap hM
let hM = new Map();
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);
}
return max_len;
}
// Driver code
let a=[0, 1, 0, 1, 1, 1, 1];
let b=[1, 1, 1, 1, 1, 0, 1];
let n = a.length;
document.write(longestCommonSum(a, b, n));
// This code is contributed by ab2127
</script>
Output
6