Count Triplets

Sort by

recency

|

806 Discussions

|

  • + 0 comments

    curious to know what is the problem with below code?

    def countTriplets(arr, r):
        right = {}
        for elem in arr:
            right[elem] = right.get(elem, 0) + 1
        
        triplets = 0
        keys = []
        for item in right.keys():
            keys += [item]
        keys.sort()
        triplets = 0
        for index in range(len(keys) - 2):
            key_1 = right[keys[index]]
            key_2 = right[keys[index + 1]]
            key_3 = right[keys[index + 2]]
            lst = [key_1, key_2, key_3]
            lst.sort()
            if r == int(keys[index +1] / keys[index]) and r == int(keys[index +2] / keys[index + 1]) :
                triplets += key_1 * key_2 * key_3
                
        return triplets
    
  • + 0 comments

    I got test 6 and 10 wrong. Any help will be appreciated!

    Here is my code:

    #!/bin/python3
    
    import math
    import os
    import random
    import re
    import sys
    
    # Complete the countTriplets function below.
    def countTriplets(arr, r):
        num_counts = {}
        triplets = 0
        # creating the hashmap
        for i in arr:
            if i in num_counts:
                num_counts[i] += 1
            else:
                num_counts[i] =1
        # counting tripplets
        
    
        for key in num_counts:
            # if ar and ar^2 is not in the map skip
            a, ar, arr = 0, 0, 0
            if key*r not in num_counts or key*r**2 not in num_counts:
                continue
            if r == 1:
                a = num_counts[key]
                triplets += math.factorial(a)//(math.factorial(a-3)*6)
            else:
                a = num_counts[key]
                ar = num_counts[key*r]
                arr = num_counts[key*r**2]
                triplets += a*ar*arr
            
        return triplets
    
    if __name__ == '__main__':
        fptr = open(os.environ['OUTPUT_PATH'], 'w')
    
        nr = input().rstrip().split()
    
        n = int(nr[0])
    
        r = int(nr[1])
    
        arr = list(map(int, input().rstrip().split()))
    
        ans = countTriplets(arr, r)
    
        fptr.write(str(ans) + '\n')
    
        fptr.close()
    
  • + 1 comment

    It was very tricky, I should say, the first task on which I've spent a significant amount of time.

  • + 1 comment

    if r = 3, can we call the following three number a triplet:

    6, 18, 54
    
  • + 1 comment

    Isn't it kind of deciving that in first line geometric progression is described to be (I,J,K) and R where J=R*I and k = R*J and THEN THERE IS A STATEMENT:

    ** I < J < K**

    Which indicates that there is no corner case for r=1 as it would not meet this requirement. Therefore there shouldn't be test case for R=1 as it does not meet the criteria described at the beggining