• + 0 comments

    i learned this elegant solution from a similar problem "count triplets", where it is a geometric series ak = aj *d, aj = ai *d:

    func beautifulTriplets(d int32, arr []int32) int32 {

    // Write your code here
    pair, triple := map[int32]int32{}, map[int32]int32{}
    var res int32
    for _, a := range arr {
        if c, ok := triple[a]; ok {
            res += c
        }
        if c, ok := pair[a]; ok {
            triple[a+d] += c
        }
        pair[a+d]++
    }
    return res
    

    }