Sort by

recency

|

1070 Discussions

|

  • + 0 comments

    Here is my O(n) c++ solution, you can watch the implementation here : https://youtu.be/vLD3N79nLSE

    int beautifulTriplets(int d, vector<int> arr) {
        map<int, int> mp;
        int result = 0;
        for (int a : arr) {
            mp[a] += 1;
            result += mp[a-d]*mp[a-2*d];
        }
        return result;
    }
    
  • + 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
    

    }

  • + 0 comments

    My PHP solution:

    function beautifulTriplets($d, $arr) {
        // Write your code here
        $hasil = 0;
        
        for ($i=0; $i < count($arr); $i++) {
            
            for ($j=$i+1; $j < count($arr); $j++) {
                
                if (($arr[$j] - $arr[$i]) == $d) {
                    
                    for ($k=$j+1; $k < count ($arr); $k++) {
                        
                        if (($arr[$k] - $arr[$j]) == $d) {
                            $hasil++;
                            break 2;
                        }
                    }
                }
            }
        }
        return $hasil;
    }
    
  • + 0 comments
    def beautifulTriplets(d, arr):
        count=0
        for i in range(0,len(arr)-2):
            for j in range(i+1,len(arr)-1):
                if(abs(arr[i]-arr[j])==d):
                    for k in range(j+1,len(arr)):
                        if(abs(arr[j]-arr[k])==d):
                            print(i,j,k)
                            count=count+1
        return count
    
  • + 0 comments

    This is the simple approach in the python language

    		l=len(arr)
        count=0 
        for i in range(l-2):
            if arr[i]+d in arr and arr[i]+(2*d) in arr:
                count+=1 
        return count