Counting triplets: solution I

I have ended up checking the solution:

def countTriplets(arr, r):
t2 = defaultdict(int)
t3 = defaultdict(int)
counter =0
for number in arr:
counter += t3[number]
t3[number*r]+=t2[number]
t2[number*r]+=1
return counter


I have ended up checking the solution:
T3 It table that given a number it return how many triplets are formed from him
T2 table given a number it returns how many times he is the second element in the triplet

We have a triplet when we have previously found duplet.
As we iterate the array, we populate t2 in the following way:

t2[number*r]+=1 // the result of multiplying the current number for the rate is a number which will the second one in a triplet

t3[number*r] += t2[r] //if the current number has already being found as the second element of triplet mo, we will have the 
Find the number of times that the current element is the second element of a potential triplet.
This the same number of times that (current element*r) will be the third element of a potential triplet.

We only count the triplet when the current element is the third element in a triplet.

At a given point in the array we will count only the elements that have been processed already. This means that it respects the triplet  i<j<k




Comments