Sort by

recency

|

1072 Discussions

|

  • + 0 comments
    public static int beautifulTriplets(int d, List<Integer> arr) {
        int tripletcount = 0;
        for(int i = 0; i < arr.size(); i++) {
            for(int j=i+1; j< arr.size(); j++) {
                if(arr.get(j) - arr.get(i) == d && findThirdNumber(arr, j, d, arr.get(j))) {
                    tripletcount++;
                    break;
                }
            }
        }
        return tripletcount;
    }
    
    private static boolean findThirdNumber(List<Integer> arr, int j, int d, int jval) {
        for(int k = j+1; k < arr.size(); k++) {
            if(arr.get(k) - jval == d) return true;
        }
        return false;
    }
    
  • + 0 comments

    Here is problem solution in Python, Java, C++, C and Javascript - https://programmingoneonone.com/hackerrank-beautiful-triplets-problem-solution.html

  • + 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;
    }