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.
Runtime: O(n + k), by doing only 1 pass of the values
Space Complexity: O(k)
We keep track of the mod values in buckets for each number we read. We can do this by creating k buckets where bucket i counts each number n where n % k = i.
Notice that each bucket has a corresponding complement bucket. That is, if we take the mod value of one bucket and add it to the mod value of another bucket, we get k.
As we come across each number, we find its corresponding complement bucket. Each number in this complement bucket can be paired with our original number to create a sum divisible by k
staticintdivisibleSumPairs(intn,intk,int[]ar){int[]bucket=newint[k];intcount=0;for(intvalue:ar){intmodValue=value%k;count+=bucket[(k-modValue)%k];// adds # of elements in complement bucketbucket[modValue]++;// saves in bucket}returncount;}
Divisible Sum Pairs
You are viewing a single comment's thread. Return to all comments →
Simple and efficient O(n+k) solution
From my HackerRank solutions which contains additional comments in code.
Runtime: O(n + k), by doing only 1 pass of the values
Space Complexity: O(k)
We keep track of the mod values in buckets for each number we read. We can do this by creating k buckets where bucket i counts each number n where n % k = i.
Notice that each bucket has a corresponding complement bucket. That is, if we take the mod value of one bucket and add it to the mod value of another bucket, we get k.
As we come across each number, we find its corresponding complement bucket. Each number in this complement bucket can be paired with our original number to create a sum divisible by k
Sample Bucket placement
For the following sample input
We have