본문 바로가기
CodeSignal

Count pairs in array whose sum is divisible by K

by Doromi 2024. 1. 10.
728x90
반응형

You are given an array of integers a and an integer k.

Your task is to calculate the number of ways to pick two different indices i < j, such that a[i] + a[j] is divisible by k. Example For a = [1, 2, 3, 4, 5] and k = 3, the output should be solution(a, k) = 4.

There are 4 pairs of numbers that sum to a multiple of k = 3: a[0] + a[1] = 1 + 2 = 3 a[0] + a[4] = 1 + 5 = 6 a[1] + a[3] = 2 + 4 = 6 a[3] + a[4] = 4 + 5 = 9

long solution(int[] a, int k) {
    long ret = 0;
    Dictionary<int,int> remainderCount = new Dictionary<int, int>();
    
    foreach(int n in a){
        int remainder = n % k;
        int complement = (k-remainder)%k;
        
        if(remainderCount.ContainsKey(complement)){
            ret += remainderCount[complement];
        }
        
        if(remainderCount.ContainsKey(remainder)){
            remainderCount[remainder]++;
        }else{
            remainderCount[remainder] = 1;
        }
    }
    return ret;
}
주어진 배열 a와 정수 k에 대해 서로 다른 인덱스 i와 j를 선택하여 a[i] + a[j]이 k로 나누어 떨어지는 경우의 수를 계산합니다. remainderCount 딕셔너리를 사용하여 나머지의 개수를 추적하고, 각 나머지에 대해 필요한 보수(complement)를 확인하여 경우의 수를 누적합니다.
if(remainderCount.ContainsKey(remainder)){
            remainderCount[remainder]++;
        }
를 늦게 해주는 이유는 중복을 막기 위함이다.

 

728x90
반응형

'CodeSignal' 카테고리의 다른 글

messageFromBinaryCode  (1) 2024.01.14
File Naming  (0) 2024.01.13
Different Squares  (0) 2024.01.09
sumUpNumbers  (0) 2024.01.08
Valid Time  (1) 2024.01.07