# Sherlock and Pairs

# Sherlock and Pairs

+ 0 comments For those who are trying in Java 8, you will need to change the given method to work with

`long`

and not`int`

.You also need to change that in the main, that is automatically generated by Hacker Rank.

+ 0 comments Can anyone help what is wrong with the following code. Only three out of 17 cases are working. https://www.hackerrank.com/challenges/sherlock-and-pairs/submissions/code/288605771

+ 0 comments Here's my Python code that passed all t he test cases:

import collections def solve(a): # if every int appears only once in the list, then return 0 if len(a) == len(set(a)): return 0 else: # create a dict where the keys are elements of list 'a' # and the values are frequencies of the elements of 'a' ctr_dict = collections.Counter(a) total_pairs = 0 for x in ctr_dict.values(): # if an integer appears 'n' times, # there are n*(n-1) distinct pairs of indices (i,j) total_pairs += x*(x-1) return total_pairs

+ 1 comment In Python 3, I recommend to use a dictionary to counts the number of repetitions for each integer. As many people have told, the number of possible different pairs if a number is repeated N times is N*(N-1), not over 2 as the combinatory coefficient nCr is, because one must count twice, i.e. (0,1) and (1,0).

def solve(a): # Write your code here a_dic = {} pairs = 0 #loop to count the number of elements for i in range(len(a)): if a[i] not in a_dic: a_dic[a[i]] = 0 #{a[i]:0} a_dic[a[i]] += 1 #{a[i]:+1} add one #loop for check whats integers taht are more than once for k in a_dic: val = a_dic[k] if val > 1: #condition more than once pairs += val * (val-1) #possible pairs n*(n-1) return pairs

+ 0 comments Ok this was stupid. Why use this line in the pre-existing code

`int result = Result.solve(a);`

when the result won't fit in an

`int`

in most cases?

Sort 128 Discussions, By:

Please Login in order to post a comment