sir, why we have not included the first case if(arr[i]==k && len==0) len=1;----this case can be used if the element itself will be the answer and the length of the subarray will be 1-----
and also if suppose the prefix[j]==prefix[i] then will we update the prefix[i] in the hash table because according to the code this will happen and if this will happen then the subarray length will not be the longest-----
Longest subarray with sum k implementation using unordered maps
@ankur8632 hey we are inserting a key, value pair only when key does not exist in the map, now if we have prefix[j]==prefix[i], then on mp.find( prefix[i])!=mp.end() will be true ,so else would not run, so value would not be updated.
For the case when arr[i]==k, then irrespective of the length, at that point suppose prefix sum is p+k, now we would have already stored value of p in the map so when we will search for p+k - k we will get the index position when p occurred, now the formula used will give the correct length.(if p occurred at i-1 we will have our length =1)
Also when arr[0]=k, then this case is handled by if(pre==k) condition.
if this resolves your doubt mark it as resolved.
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.