Sort by

recency

|

1073 Discussions

|

  • + 0 comments
    def beautifulTriplets(d, arr):
        # Write your code here
        n = len(arr)
        c = 0
        lookup = set(arr)
        for i in range(n - 2):
            first = arr[i]
            second = first + d
            third = second + d
            if second in lookup and third in lookup:
                c += 1
        return c
    
  • + 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
    

    }