Files

52 lines
1.5 KiB
Java
Raw Permalink Normal View History

2017-03-10 01:10:37 -06:00
// Author: Rodney Shaghoulian
2018-07-27 16:45:56 -07:00
// Github: github.com/RodneyShag
// HackerRank: hackerrank.com/RodneyShag
2017-03-10 01:10:37 -06:00
/*
2017-04-05 18:42:35 -05:00
Time Complexity: O(n + k)
2017-03-10 01:10:37 -06:00
Space Complexity: O(k)
2017-04-05 18:42:35 -05:00
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.
2017-03-10 01:10:37 -06:00
2017-04-05 18:42:35 -05:00
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".
2017-03-10 01:10:37 -06:00
Bucket Complement Bucket
------ -----------------
0 0
1 k-1
2 k-2
3 k-3
...
k-3 3
k-2 2
k-1 1
2017-04-05 18:42:35 -05:00
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*
2017-03-10 01:10:37 -06:00
*/
import java.util.Scanner;
public class Solution {
2017-09-11 09:32:17 -07:00
public static void main(String[] args) {
2017-03-10 01:10:37 -06:00
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int k = scan.nextInt();
2017-04-05 18:42:35 -05:00
int [] bucket = new int[k];
2017-03-10 01:10:37 -06:00
int count = 0;
for (int i = 0; i < n; i++) {
int modValue = scan.nextInt() % k;
2017-04-05 18:42:35 -05:00
count += bucket[(k - modValue) % k]; // adds # of elements in complement bucket
bucket[modValue]++; // saves in bucket
2017-03-10 01:10:37 -06:00
}
scan.close();
System.out.println(count);
}
}