Simple c++ hashing


#1

int Solution::solve(vector &a) {

int n=a.size();
int s=0,mx=0;
unordered_map<int,int> m;

for(int i=0;i<n;i++){
    if(a[i]==0){
        s--;
    }   
    else{
        s++;
    }
    if(s==1){
        mx=i+1;
    }
    else if(m.find(s)==m.end()){
        m[s]=i;
    }
    if(m.find(s-1)!=m.end()){
        mx=max(mx,i-m[s-1]);
    }
}

return mx;

}


#2

Why are we finding S-1? I understand we need to make the total sum 1 or more so that 1’s are greater than 0’s. But then it can be S-2, S-3 and so on also. Why are we particularly looking for just one extra ‘1’ in the subarray?


#3

This is because we need to find the length of the longest subarray. The longest subarray would be the one in which the count of 0’s would be one less than the count of 1’s i.e. we need to find all those subarrays with sum as 1.


#4

Why didn’t we save m[1]?? Isn’t it necessary?


#5

can some one help with Help BUTTON in interviewbit i no idea where its located.