while updating the map, m[prefixSum] = index , we are not checking if the prefixSum index is already present.So if prefixSum is already present in the map and we update prefixSum with new index, it won’t be the leftmost occurrence of prefixSum.So it gives wrong answer
Code implementation is wrong
hello @sahazeer123
if prefSum is already present in map then only if statement will execute and there we are not updating map.
so the given code will work fine.
Please check for test case k = 3 arr[] = {1,2,3,-3,-2,-1,4,1,0,1} will give 6 but correct output is 8
please tell me starting and ending indices of the subarray with lenght 8.
yeah answer should be 8.
please send ur code .
#include
#include <unordered_map>
using namespace std;
int main() {
//code
int no_test;
cin >> no_test;
for(int test = 0;test < no_test;++test)
{
int n,k;
cin >> n >> k;
int nums[n];
for(int i = 0;i < n;++i)
cin >> nums[i];
unordered_map<int,int>preSum;
int currentSum = 0;
int len = 0;
for(int i = 0;i < n;++i)
{
currentSum += nums[i];
if(currentSum == k)
len = max(len,i+1);
if(preSum.find(currentSum - k) != preSum.end())
len = max(len,i-preSum[currentSum-k]);
if(preSum.find(currentSum) == preSum.end())
preSum[currentSum] = i;
}
cout << len << endl;
}
return 0;
}
But the code discussed on the video will give 6 as output.Please check
please share the code that is discussed if it is different from above one.
i will check
yeah it is bit wrong.
there should be if statement for checking currntsum in map in the place of else.
please share the title for this video.i will inform this to the team.
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.