Longest Subarray sum zero vs K

In finding the longest subarray with zero-sum, we checked for arr[i]==0 (if a single element subarray is 0). But we are not doing that in the subarray sum to be k problem?

@ankurguria hey that case is handled in when we use the map, suppose the sum till i-1 is a, now at i i encounter k, now pre will be a+k, on searching the map for “a+k-k” we will get “i-1” and subtracting it with i will give us 1.
If this resolves your doubt mark it as resolved.

What if there is k at arr[0]; but we haven’t inserted 0 (as arr[0] - k == 0) in the map. We wouldn’t be updating the length to be 1. Am I right?

1 Like

@Abhinav2604 if arr[0]=k, then pre also equals to k, now

if(pre==k) len=max(len,i+1);

will cause the updation of the length.
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.