We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
First of all, we need to notice that (A + B) % K = ([A/K] * K + A % K + [B/K] * K + B % K) % K = (A % K + B % K) % K (i.e. remainder of the sum equals to the remainder of the sum of the remainders). What it gives us is that in order to find B knowing A where (A + B) % K it's enough just to look at A % K and B % K.
Then, consider we are at some item A[j] right now and we need to calculate how many pairs this A[j] makes with all the previous items A[i], i < j. That is actually a number of items A[i], i < j where A[i] % K complements A[j] % K. By "complements" here I mean that (A[i] % K + A[j] % K) % K == 0. That actually means that they are either both == 0 or their sum == K. (K - A[j] % K) % K effectively calculates this complement.
Wrapping it up, we divide all the items in A into buckets by A[i] % K value. This gives us the ability at each step to see how many pairs we have involving some item A[i]. Iterating the array once and calculating only pairs on the left helps us not to count one pair two times while still covering all the combinations.
Hope this helps.
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Divisible Sum Pairs
You are viewing a single comment's thread. Return to all comments →
First of all, we need to notice that
(A + B) % K = ([A/K] * K + A % K + [B/K] * K + B % K) % K = (A % K + B % K) % K
(i.e. remainder of the sum equals to the remainder of the sum of the remainders). What it gives us is that in order to find B knowing A where(A + B) % K
it's enough just to look atA % K
andB % K
.Then, consider we are at some item
A[j]
right now and we need to calculate how many pairs thisA[j]
makes with all the previous itemsA[i], i < j
. That is actually a number of itemsA[i], i < j
whereA[i] % K
complementsA[j] % K
. By "complements" here I mean that(A[i] % K + A[j] % K) % K == 0
. That actually means that they are either both == 0 or their sum == K.(K - A[j] % K) % K
effectively calculates this complement.Wrapping it up, we divide all the items in
A
into buckets byA[i] % K
value. This gives us the ability at each step to see how many pairs we have involving some itemA[i]
. Iterating the array once and calculating only pairs on the left helps us not to count one pair two times while still covering all the combinations.Hope this helps.