Sort by

recency

|

1064 Discussions

|

  • + 0 comments
     
     public static int beautifulTriplets(int d, List<Integer> arr) {
        // Write your code here
         int triplets=0;
         for(int i=0;i<arr.size();i++){
             int sum = d+arr.get(i);
             if(arr.contains(sum)){
                sum=sum+d;
                if(arr.contains(sum)){
                    triplets++;
                }
             }
        }
            return triplets;
         }
        
    
    }
    

    `

  • + 0 comments

    My python code (only runs last for loop if needed):

    def beautifulTriplets(d, arr):
        ans = 0
        for a in range(len(arr)):
            for b in range(a + 1, len(arr)):
                if arr[b] - arr[a] == d:
                    for c in range(b + 1, len(arr)):
                        if arr[c] - arr[b] == d:
                            ans += 1
        return ans
    
  • + 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
    def beautifulTriplets(d, arr):
        c=0
        n=len(arr)
        for i in range(n):
            for j in range(i+1,n):
                if arr[j]-arr[i]==d:
                    for k in range(j+1,n):
                        if arr[k]-arr[j]==d:
                            c+=1
        return c
    
  • + 0 comments

    C++ Solution

    int beautifulTriplets(int d, vector<int> arr) {
      int res = 0;
      for(auto it = arr.begin(); it < arr.end(); it++) {
        auto a = find(it+1, arr.end(), *(it)+d);
        if(a != arr.end()) {
          auto b = find(a+1, arr.end(), *(a)+d);
            if(b != arr.end()) res++;
        }
      }
      return res;
    }