Divisible array problem


test case 3 is not passing giving incorrect anser

array2[i]=(array[i-1] + array2[i-1])%n;
We need to take modulo at this step also.
This will help in preventing overflow, also in case where sum comes to be a big negative number this will help in bringing it down,
Eg array2[i]=-150, n=51
now array3[i]=(-150+51)%51 =-48(but we need positive number so)
so
array2[i]=array2[i]%n
this will make
array2[i]=-48
array3[i]=(array2[i]+n)%n=3

Please mark your doubt as resolved if this solves your doubt.

can you send the test case 3 inputs

also when i did not took modulo there the index may come negative of pre array so why does other test cases passes

Every testcase does not contain every cases and corner cases, that is why there are multiple test case.

So what is the main aim to take modulo there only one reason overfolw ??

overflow and negative number as explained above, when you write code you need to write it keeping in mind every possible case(even if the occurrence of case is rare)


According to video in the line 23 is we can take modulo of sum till that index like this… How this is working…

What you have written is essentially the same, you just used an entire array for calculating sum, and have shifted the entire sum position by 1 which does not matter.

I am talking about what is written in the video that line I want to. understand from line 23 to 25 how this is working…

We take the input, then we directly add it to sum, now sum at this point will contain the same value as that of array2[i+1], now we take the modulo of sum, similar to taking mod of array2[i+1] then again we take mod by adding n to adjust negative number same as (array2[i+1]+n)%n, now it does pre[sum]++ that is equivalent to array3[array2[i+1]]++.
As I said both are doing exactly the same thing, this code is just a bit optimised it is saving space and extra for loops.
If this solves your doubt mark it as resolved.

1 Like

thanks sir for your crystal clear explanantion…

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.