Longest Span in two Binary Arrays | Practice | GeeksforGeeks

Given two binary arrays arr1[] and arr2[] of same size N. Find 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]. 
 
Example 1:
Input:
N = 6
Arr1[] = {0, 1, 0, 0, 0, 0}
Arr2[] = {1, 0, 1, 0, 0, 1}
Output: 4
Explanation: The longest span with same
sum is from index 1 to 4 following zero 
based indexing.

 
Your Task:
You don't need to read input or print anything. Complete the function longestCommonSum() which takes two arrays arr1, arr2 and integer n as input parameters and returns the length of the longest common span.
 
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(N)
 
Constraints:
1 <= N <= 105
0 <= Arr1[i], Arr2[i] <= 1
0
premranjan88046
This comment was deleted.
+1
sivasret2 weeks ago
Arr1[] = {0, 1, 0, 0, 0, 0}
Arr2[] = {1, 0, 1, 0, 0, 1}
 
How the longest span for above two arrays is 4 . It should be 2 right ?
0
anirbanhaldar6002 weeks ago
Easy Solution C++ → Time : O(n) , Space : O(1)#
>> First find difference (arr1 - arr2) between two arrays (the new array will have -1 or 0 or 1).
>> Now solve the problem as, “Subarray sum 0”
>> Remember to store the indices as they will help to calculate subarray size.
int longestCommonSum(bool arr1[], bool arr2[], int n) {
    int a[n];
    for(int i = 0; i < n; i++) a[i] = (int) arr1[i] - (int) arr2[i];
    unordered_map<int, int> m;
    int dist = 0 + !a[0];
    m.insert({a[0], 0});
    for(int i = 1; i < n; i++){
        a[i] += a[i-1];
        if(a[i] == 0){
            if(dist < i+1) dist = i+1;
        }
        else if(m.find(a[i]) != m.end()){
            int x = m.find(a[i]) -> second;
            if(dist < i-x) dist = i - x;
        }
        else m.insert({a[i], i});
    }
    return dist;
}
#Space complexity : As they have given Boolean array instead of binary array, so I am forced to take an integer array to store “-1”, So space complexity for this particular problem is O(n) otherwise if they have given proper integer array, then the algorithm could be implemented inplace and the space would be O(1).
0
harshpandeyalfa23 weeks ago
C++
(0.7sec)
int longestCommonSum(bool arr1[], bool arr2[], int n) {       int arr[n];       for(int i=0;i<n;i++)         arr[i]=arr1[i]-arr2[i];               int ps=0;       int res=0;       unordered_map<int,int> s;       for(int i=0;i<n;i++)       {           ps+=arr[i];           if(ps==0)            res=i+1;           else if(s.find(ps)==s.end())            s.insert({ps,i});           else if(s.find(ps)!=s.end())            res=max(res,i-s[ps]);       }       return res;   }
0
shreyansh28124 months ago
Is it not efficient if we use map to solve this problem?
 
I have done it like this...
 
 int longestCommonSum(bool arr1[], bool arr2[], int n) {              unordered_map<int,int> m;       int sum = 0;       int result = 0;              for(int i = 0; i < n; i++)       {           int diff = arr1[i]-arr2[i];           sum += diff;                      if(sum == 0)           {               result = max(result,i+1);           }                      if(m.find(sum) != m.end())           {               result = max(result, i - m[sum]);           }
           else           {               m[sum] = i;           }       }              return result;   }
 
 
 
+1
badgujarsachin834 months ago
 int longestCommonSum(bool arr1[], bool arr2[], int n) {
            // code here 
            int v[n];
            for(int i=0;i<n;i++){
                v[i]=arr1[i]-arr2[i];
            }
            int maxi=0,sum=0;
            unordered_map<int,int> mp;
            for(int i=0;i<n;i++){
                sum+=v[i];
                if(sum==0){
                    maxi=i+1;
                }
                if(mp.find(sum)!=mp.end()){
                    maxi=max(maxi,i-mp[sum]);
                }else{
                    mp[sum]=i;
                }
            }
            return maxi;
    }
0
abhishekpanwar6976 months ago
first find the difference of both arrays than find the longest subarray with sum 0 or equal number of zeros and one's
 
int longestCommonSum(bool a[], bool b[], int n) {       int v[n];       for(int i=0;i<n;i++)       {           v[i]=a[i]-b[i];       }       int maxi=0,sum=0;       unordered_map<int,int>mp;       for(int i=0;i<n;i++)       {           sum+=v[i];           if(sum==0)           maxi=i+1;           if(mp.find(sum)!=mp.end())           maxi=max(maxi,i-mp[sum]);           else           mp[sum]=i;       }       return maxi;   }
0
prashantsketch7 months ago
class Solution:
	def longestCommonSum(self, arr1, arr2, n): 
		# code here 
		max_len=0
		sum1=0
		sum2=0
		diff={}
		for i in range(n):
		    sum1+=arr1[i]
		    sum2+=arr2[i]
		    current_diff=sum1-sum2
		    if current_diff==0:
		        max_len=i+1
		    elif current_diff not in diff:
		        diff[current_diff]=i
		    else:
		        length=i-diff[current_diff]
		        max_len=max(max_len,length)
		return max_len
0
akjha4987 months ago
O(N),O(N)
int longestCommonSum(bool arr1[], bool arr2[], int n) {           // code here           int temp[n];           for(int i=0;i<n;i++){               temp[i]=arr1[i]-arr2[i];           }           int pre_sum=0,res=0;           unordered_map<int,int> m;           for(int i=0;i<n;i++){               pre_sum+=temp[i];               if(pre_sum==0){                   res=i+1;               }               if(m.find(pre_sum)==m.end()){                   m[pre_sum]=i;               }               if(m.find(pre_sum)!=m.end()){                   res=max(res,i-m[pre_sum]);               }           }          return res;    }
0
Manasvin_Sharma1 year ago
Manasvin_Sharma
C++ 0.01 Solution
#include<bits stdc++.h="">using namespace std;
int main(){ios_base::sync_with_stdio(false);    cin.tie(NULL);
int queries;cin>>queries;while(queries--){int n;cin>>n;
int arr1[n],arr2[n],temp[n],sum=0,count=0,temp_count;
for(int i=0;i<n;i++) cin="">>arr1[i];
for(int i=0;i<n;i++) cin="">>arr2[i];
for(int i=0;i<n;i++) temp[i]="arr1[i]-arr2[i];" for(int="" size="1;size&lt;=n;size++)" {="" temp_count="0;sum=0;" for(int="" i="0;i&lt;size;i++)" {="" sum+="temp[i];" temp_count++;="" }="" if(sum="=0)" count="max(count,temp_count);" for(int="" i="size;i&lt;n;i++)" {="" sum="sum+temp[i]-temp[i-size];" if(sum="=0)" count="max(count,temp_count);" }="" }="" cout<<count<<"\n";="" }="" return="" 0;="" }="">
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.