Posts Count pairs in array divisible by K
Post
Cancel

Count pairs in array divisible by K

PROBLEM DESCRIPTION

You are given a number N. Find the total number of setbits in the numbers from 1 to N.

geeksforgeeks

SOLUTION

snapshot

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
class Solution
{
    public static long countKdivPairs(int nums[], int n, int k)
    {

        //to store the count of numbers for remainder [0,k-1]
        Map<Long, Long> map = new HashMap<>();

        //init, remainder count
        for(int i=0; i<n; i++){
            long remainder = nums[i]%k;
            map.put(remainder, map.getOrDefault(remainder, 0L)+1);
        }

        //init answer
        long total=0;

        //if there are elements which has 0 as the remainder, we can pair them together in nC2 ways
        if(map.containsKey(0L)){
            total = pickTwoWays(map.get(0L));
        }
       
        //other pairs which can be formed using remainder (i) and (k-i)
        long i=1;
        long j=k-1;
        
        while(i<j){
            
            if(map.containsKey(i) && map.containsKey(j)){
                total = total + (map.get(i) * map.get(j));
            }
            
            i++;
            j--;
            
        }
        
        //if k is even, we can form more pairs using elements which have the remainder as k/2
        long mid = k/2;
        if(k%2 == 0 && map.containsKey(mid)){
            total = total + pickTwoWays(map.get(mid));
        }

        return total;
    }
    
    //number of ways to pick 2 elements from n elements = nC2
    public static long pickTwoWays(long n){
        return (n*(n-1))/2;
    }
    
}
This post is licensed under CC BY 4.0 by the author.