Sort by

recency

|

2443 Discussions

|

  • + 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;
    }
    
  • + 0 comments

    Hi here is my Python solution. I can take any suggestions .

    def divisibleSumPairs(n, k, ar):
    # Write your code here
    count=0
    for index ,i in enumerate(ar):
        for index2 ,item in enumerate(ar):
            if(index!=index2):
                 if ((i+item)%k==0):
                    count=count+1
    
        print(int(count/2))
    return int(count/2)
    
  • + 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;
    }
    
  • + 1 comment
    def divisibleSumPairs(n, k, ar):
        # Write your code here
        count = 0
        for i in range(0, n) :
            
            for j in range(1, n): 
                if i < j and (ar[i] + ar[j]) % k == 0: 
                        count+= 1
                    
        return count        
    
  • + 0 comments

    C# Solution: Explanation: we sort the array, and after the array is in a non descending order, we apply the two pointer method, "i" points to the current number and "j" starts from the end and works its way backwards until the number "ar[i] + ar[j] < k" (after that there is no reason to continue, because none of the pairs will be divisible by k)

            ar.Sort();
            int answer = 0;
            int i = 0;
            int j = n-1;
            while (i < j) {
                if ((ar[i] + ar[j])%k == 0) {
                    answer++;
                }
                if (ar[i] + ar[j] < k || j==i+1) {
                    i++;
                    j=n-1;
                } else {
                    j--; 
                }
            }
            return answer;