Hackerrank - Divisible Sum Pairs Solution
1 min read

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))

Enjoying these posts? Subscribe for more


Adblocker detected! Please consider reading this notice.

We've detected that you are using AdBlock Plus or some other adblocking software which is preventing the page from fully loading.

That's okay. But without advertising-income, we can't keep making this site awesome.

We don't have any banner, Flash, animation, obnoxious sound, or popup ad. We do not implement these annoying types of ads!

We need money to operate the site, and almost all of it comes from our online advertising.

Please add thepoorcoder.com to your ad blocking whitelist or disable your adblocking software.

×