Sort by

recency

|

2427 Discussions

|

  • + 0 comments
    public static int divisibleSumPairs(int n, int k, List<Integer> ar) {
            
            Map<Integer,Integer> mp=new HashMap<>();
            int cnt=0;
            
            for(int i=0;i<ar.size();i++){
                int rem=ar.get(i)%k;
                int com=(k-rem==k?0:k-rem);
                if(mp.containsKey(com)){
                    cnt+=mp.get(com);
                    
                }
                mp.put(rem,mp.getOrDefault(rem,0)+1);
                
            }
            
            return cnt;
    
        }
    
    }
    ****
    
  • + 0 comments

    python

    def divisibleSumPairs(n, k, ar):
        count = 0
        for idx in range(len(ar)):
            for jdx in range(idx+1, len(ar)):
                if (ar[idx]+ar[jdx])%k==0:
                    count+=1
        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

    java(8)

    public static int divisibleSumPairs(int n, int k, List<Integer> ar) {
        // Write your code here
        int ways = 0;
        for (int i = 0; i < ar.size(); i++) {
    
            for (int j = i + 1; j < ar.size(); j++) {
                if ((ar.get(i) + ar.get(j)) % k == 0) {
                    ways++;
                }
    
            }
    
        }
        return ways;
    }
    
  • + 0 comments

    O(n+k)

    def divisibleSumPairs(n, k, ar):
        from collections import Counter
        modulo_count = Counter(num % k for num in ar)
        count = 0
        for i in range(k):
            j=-i % k
            
            num1 = modulo_count.get(i, 0)
            num2 = modulo_count.get(j, 0)
            
            if i>j or num1==0 or num2==0:
                continue
    
            if i==j:
                count+= num1*(num1-1)//2
            else:
                count+=num1*num2
        return count