Sort by

recency

|

2446 Discussions

|

  • + 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])
    
  • + 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

    C# solution

    public static int divisibleSumPairs(int n, int k, List<int> ar)
        {
            int result = 0;
            
            for(int i = 0; i < ar.Count; i++)
                for(int j = (i + 1); j < ar.Count; j++)
                    if((ar[i] + ar[j]) % k == 0) result++;
            
            return result;
        }
    
  • + 0 comments

    Perl:

    sub divisibleSumPairs {
        my ($n, $k, $s) = @_;
    
        my $res = 0;
        for (my $i = 0; $i < $n; $i++) {
            for (my $j = 0; $j < $n; $j++) {
                $res++ if ($i < $j && (($s->[$i] + $s->[$j]) % $k) == 0 );
            }
        }
        return $res;
    }