+ 1

we have to find total number of pairs in matrix a whose difference is divible by 200 "(a[i]-a[j] is multible of 200)".......

class Solution { static long countPairs(int N, int a[] ) {//N is size of array a // code here long count=0; long [] y=new long[200]; for(int i=0;i<N;i++) { y[a[i]%200]++; // what is this code doing explain } for(int x=0;x<200;x++) { count+=(y[x]*(y[x]-1l))/2l; // i cannot understand what's happening here } return count; }}

27th Feb 2023, 6:45 AM
Manish
Manish - avatar
2 ответов
+ 1
Pls clarify your question. First, change the title to a short explanation of what the question is about. Then, use the description to explain your difficulties. To add code to the question description, pls save the code as public in Code Playground, then use "+" button to link it inside the question description. Well written questions attract better answers.
27th Feb 2023, 12:29 PM
Emerson Prado
Emerson Prado - avatar
+ 1
Manish this is a sophisticated technique that I have never seen before. It begins with the idea that if two numbers have the same remainder after dividing by 200, then their difference will be a multiple of 200. For instance if you divide the following numbers by 200, all have remainder 4: {4, 204, 404, 604, 804}. The difference between any two numbers in this set will be an exact multiple of 200. The same would be true for any other set of numbers where their remainders match each other. The first loop builds counts of how many numbers have the same remainders of 0...199. The second loop adds up how many pairs you can make from each of those sets. Using my example above, there are 5 numbers that have remainder 4. From that set you can make 5*(5-1)/2 = 10 unique pairs. The loop does that calculation for each of the sets and adds them all up. BTW, there are a couple extraneous characters in the second loop that would cause a syntax error. It should be count+=(y[x]*(y[x]-1))/2
27th Feb 2023, 8:53 PM
Brian
Brian - avatar