- Count Triplets
- Discussions

# Count Triplets

# Count Triplets

+ 0 comments Here is my solution but I still fail two test cases, does anyone have any recommendation to fix it, many thanks!

`def countTriplets(arr, r): dict={} for i in arr: if not dict.get(i): dict[i]=[i*r,1] else: dict[i][1]+=1 temp=list(dict.keys()) print (temp) print (dict) result=0 for i in temp: if r==1: result+=dict.get(i)[1]*(dict.get(i)[1]-1)*(dict.get(i)[1]-2)/6 elif dict.get(dict.get(i)[0])!=None and dict.get(dict.get(dict.get(i)[0])[0])!=None: first=i second=dict.get(first)[0] third=dict.get(second)[0] result+=dict.get(first)[1]*dict.get(second)[1]*dict.get(third)[1] return int(result)`

+ 1 comment Very simple Python3 solution!

from collections import defaultdict freq = defaultdict(int) pair = defaultdict(int) def countTriplets(arr, r): count = 0 for val in arr: if val % (r*r) == 0: count += pair[val // r] if val % r == 0: pair[val] += freq[val // r] freq[val] += 1 return count

+ 0 comments I think I get it but this is way harder than interview questions should be. For one thing you're supposed to realize that you have to traverse the array backwards. If you don't realize that you just won't solve the problem

Actually I don't get it

+ 1 comment Question:

Theres a constraint saying i < j < k.

In this case then the test case where the given ratio is 1 then the answer should be automatically 0 no? Since a number multiplied by 1 is the same number, the triplets would be i = j = k. I am failing a test (where I get a completely different result than expected) and when I look at it its just a huge array with the same number and ratio = 1. but according to this logicall triplets should have the same number, which doesnt satisfy the i < j < k requirement

+ 1 comment def countTriplets(arr, r): count = 0 elements = set(arr) for i in elements: first = i second = i*r third = i*r*r if (second in elements) and (third in elements): count += arr.count(first) * arr.count(second) * arr.count(third) return count

i am facing an errorwhen r = 1. could someone please help me with it

Sort 773 Discussions, By:

Please Login in order to post a comment