Hackerrank - Divisible Sum Pairs Solution

Hackerrank - Divisible Sum Pairs Solution

You are given an array of  integers, , and a positive integer, . Find and print the number of  pairs where  and  +  is divisible by .

For example,  and . Our three pairs meeting the criteria are  and .

Function Description

Complete the divisibleSumPairs function in the editor below. It should return the integer count of pairs meeting the criteria.

divisibleSumPairs has the following parameter(s):

  • n: the integer length of array
  • ar: an array of integers
  • k: the integer to divide the pair sum by

Input Format

The first line contains  space-separated integers,  and .
The second line contains  space-separated integers describing the values of .

Constraints

Output Format

Print the number of  pairs where  and  +  is evenly divisible by .

Sample Input

6 3
1 3 2 6 1 2

Sample Output

 5

Explanation

Here are the  valid pairs when :

Solution in Python

from collections import Counter

def divisibleSumPairs(n, k, ar):
    b = set()
    c = Counter(i%k for i in ar)
    count = 0
    for i,j in c.items():
        if not i or i==k/2:
            count += j*(j-1)//2
        elif i not in b and k-i in c:
            count += j*c[k-i]
        b.add(k-i)
    return count

n,k = map(int, input().split())
ar = list(map(int, input().rstrip().split()))
print(divisibleSumPairs(n, k, ar))

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe