Count Triplets

  • + 0 comments

    Recursive solution:

    def countTriplets(arr, r):
        sys.setrecursionlimit(10**6) #Avoid recursion error
        def rec_function(index, seconds, thirds, count):
            if index >= len(arr):
                return count
            i = arr[index]
            if i in thirds:
                count += thirds[i]
            if i in seconds:
                thirds[i * r] = thirds.get(i * r, 0) + seconds[i]
            seconds[i * r] = seconds.get(i * r, 0) + 1
            return rec_function(index + 1, seconds, thirds, count)
        
        return rec_function(0, {}, {}, 0)