Sort by

recency

|

2448 Discussions

|

  • + 0 comments

    In C# 100%

    public static int divisibleSumPairs(int n, int k, List<int> ar)
        {
            int count = 0;
            int[] remainders = new int[k]; 
            
            for (int i = 0; i < n; i++)
            {
                int currentRemainder = ar[i] % k;
                if (currentRemainder < 0) currentRemainder += k;
                int complement = (k - currentRemainder) % k; 
                count += remainders[complement];
                remainders[currentRemainder]++;
            }
            
            return count;
        }
    
  • + 0 comments

    Python

    def divisibleSumPairs(n, k, ar):
        ar_mod = [i%k for i in ar]
        count_mod = {}
        for i in ar_mod:
            if i not in count_mod:
                count_mod[i] = 0
            count_mod[i] += 1
        
        count = 0
        
        for i in ar_mod:
            count_mod[i] -= 1
            
            if i != 0:
                sub = k-i
            else:
                sub = 0
            
            if sub in count_mod:
                count += count_mod[sub]
        
        return count
    
  • + 0 comments

    Here is my c++ solution, you can whatch the explanation here: https://youtu.be/aDv1iUSgnd8

    Solution 1 : O(n^2)

    int divisibleSumPairs(int n, int k, vector<int> ar) {
        int result = 0;
        for(int i = 0; i < ar.size() - 1; i++){
            for(int j = i + 1; j < ar.size(); j++){
                if( (ar[i] + ar[j]) % k == 0) result++;
            }
        }
        return result;
    }
    

    Solution 2 : O(n)

    int divisibleSumPairs(int n, int k, vector<int> ar) {
        map<int, int> mp;
        for(int i = 0; i < ar.size(); i++){
            mp[ar[i] % k]++;
        }
        int result = 0;
         for(int i = 0; i <= k/2; i++){
            if(i == 0 || i*2 == k) result += (mp[i] * (mp[i] - 1)) / 2;
            else result += mp[i] * mp[k - i]; 
        }
        return result;
    }
    
  • + 0 comments

    def divisibleSumPairs(n, k, ar):

    possible_comb = list()
    
    for comb in itertools.combinations(ar, 2):
        if (comb[0] + comb[1]) % k == 0:
            possible_comb.append(comb)
    
    return len(possible_comb)  
    
  • + 0 comments

    Using Python


    from itertools import combinations
    
    def divisibleSumPairs(n, k, ar):
        pairs = list(combinations(ar, 2))
        return len([p for p in pairs if sum(p) % k == 0])