Divisible Sum Pairs

Sort by

recency

|

199 Discussions

|

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

    O(n) in Golang

    func divisibleSumPairs(_ int32, k int32, ar []int32) int32 {
    	// Write your code here
    
    	// A map that stores the remainder of each value
    	remainderMap := make(map[int32]int32)
    	// The number of found solution
    	count := int32(0)
    
    	for _, value := range ar {
    		remainder := value % k
    		/*
    		   A complement remainder is a number whose initial number y
    		   when added to a value x returns a multiple of k
    		*/
    		complementRemainder := (k - remainder) % k
    
    		// A value whose remainder is the complement remainder
    		remValue, exists := remainderMap[complementRemainder]
    
    		//We add the number of values that align to the condition
    		if exists {
    			count += remValue
    		}
    
    		//Check if there's duplicate remainder
    		//If A dup exists we add the number of duplicates available
    		theDup, existsADuplicate := remainderMap[remainder]
    		if existsADuplicate {
    			remainderMap[remainder] = theDup + 1
    		} else {
    			remainderMap[remainder] = 1
    		}
    	}
    
    	return int32(count)
    }
    
  • + 0 comments

    int divisibleSumPairs(int n, int k, int ar_count, int* ar)

    I think we do not need n and ar_count together as input. Bot are redundant. Both give the size of the array.

  • + 0 comments

    Python Solution using dict: def divisibleSumPairs(n, k, ar): # Write your code here remainder_count = {} valid_pairs = 0

    for num in ar:
        remainder = num % k
        complement = (k - remainder) % k
        if complement in remainder_count:
            valid_pairs += remainder_count[complement]
        if remainder in remainder_count:
            remainder_count[remainder] += 1
        else:
            remainder_count[remainder] = 1
    return valid_pairs
    
  • + 0 comments

    A naive rust approach:

    fn divisibleSumPairs(n: i32, k: i32, ar: &[i32]) -> i32 {
        let mut x = 1;
        let mut n_pairs = 0;
        
        for &i in ar {
            for &j in &ar[x..] {
                if (i + j) % k == 0 {
                    n_pairs += 1;
                }
            }
            x += 1;
        }
        n_pairs
    }