Some test cases failing

I have looked at prateek bhaiya’s answer to this and for that all test cases pass. I have his logic in commented for below, but I don’t get how my logic is wrong:
In his solution: sum = (sum+n)%n is essentially (sum%n + n%n)%n where n%n=0, so it effectively taking the mod twice for sum.

In my logic I need to get the remainder of (sum+val)%size, so I do (sum%size + val%size)%size, just as an extra step I take the mod again while adding to the frequency table.

Sometimes my test cases fail, sometime they dont complete.

#include
using namespace std;

int main() {
int num;
cin>>num;
for(int k=0;k<num;k++)
{
long long int size;
cin>>size;
long long int sum=0;
long long int freq_table[size]{0};
//as cumm_sum of 0 is already found
freq_table[0] = 1;
for(int i=0;i<size;i++)
{
long long int val;
cin>>val;
//sum = sum+val;
//sum = sum%size;
//sum = (sum+size)%size;
sum = sum%size;
val = val%size;
sum = (sum+val)%size;
freq_table[sum%size]++;
}
long long int sum_arrays = 0;
for(int i=0;i<size;i++)
{
sum_arrays = sum_arrays+(freq_table[i]*(freq_table[i]-1)/2);
}
cout<<sum_arrays<<endl;
}
return 0;
}

completely agree with your point
the only reason we add n
is because we are trying to access that index
and we can in no way access -2
so (-2+n)%n as u said will have made no difference on the original expression
but it makes the index +ve and hence pre[sum]++ can be done
else we will get an error
sum = -2 N= 5

3%5

kya hoga

3

agr tu sirf -2%5 karega to -2 walla

index refer hofa

modulo ki yeh property hoti h ki jo numerator ka sign hoga vo final answer ka irrespective of the denominator

so -2%5 + 3%5 nhi karna h is bar

it is meant to be (-2+5)%5

Oh right. That seems legit. As it can have negative numbers as input.
Thanks for the help.

1 Like