Longest Subarray With Sum K Implementation

I think we need to insert in the map irrespective of the fact that pre-k is present or not. I mean, mp[pre]=i should be outside the if condition in the given code.

Hello @raj.bmp.333,

No, I don’t think so.
if you would insert in the map irrespective of the fact that pre-k is present or not.
Then, it will overwrite the value.
Please, refer to the previous video in the course to understand why Sir has done so.

If you feel that what you have said is still correct then give an example in support of your statement.

Hope, this would help.

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.

Take an example where prefix sum array looks like: 2 3 5 6 4 7 8 10 ( original array being: 2 1 2 1 -2 3 1 )
and k=3. In this case ans should be 4 but the code will out output 2.
When pre sum is 5 it checks whether 2 is present or not ans since 2 is present, 5 is not inserted in hash table. Now when prefix sum is 8 it checks whether 5 is present or not and since 5 was not inserted, it won’t consider a sub array of length 4. And will return 2.
Please consider this case.

Hello @raj.bmp.333,

Yes, you are right.

But, mp[pre]=i should be outside the if condition in the given code.I’ll forward the same to your mentors. will not help.
You need to check if mp[pre] is not present in the map then only you will insert the pre into the map.
Reason:
As you have to find the maximum length subarray, so the first occurrence of that pre will give the maximum length.
Overwriting it with new value give a smaller length for the next computation.
(the second occurrence of the same pre will be at the left of previous occurence)

Thanks for pointing out the mistake in the code.
This shows how attentive you are.
They will soon correct it.:blush:

1 Like

Thanks for clarification.

The code which is implemented by sir in the video
is providing different output for the test case
10 3
1 2 3 -3 -2 -1 4 1 0 1
n =10 k=3
Output should be 8 but output provided by code is 6.
Please clarify.