We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
defcountTriplets(arr,r):a=0cpairs=dict()cnumber=dict()foriinreversed(arr):# keys of cpairs = values in arr, corresponding values of cpairs = number of possible pairs with the number <key's number> whereby the 2nd element of each pair = <key's number>*r, and s.t. the keys occur after i in the list arr.# values of cnumber = the number of times that <key's number> has been encountered so far when looking at arr in reverse.ifi*rincpairs:a+=cpairs[i*r]ifnot(iincnumber):cnumber[i]=0ifi*rincnumber:ifiincpairs:cpairs[i]+=cnumber[i*r]else:cpairs[i]=cnumber[i*r]# Necessary to put this line right at the end of the loop to properly handle the edge case r==1cnumber[i]+=1returna
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Count Triplets
You are viewing a single comment's thread. Return to all comments →
Alternative without using the collections module: