Sort by

recency

|

1068 Discussions

|

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

    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

    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
    
  • + 0 comments

    Python one-liner:

    def beautifulTriplets(d, arr):
        return sum(arr.count(n) * arr.count(n + d) * arr.count(n + d + d) for n in set(arr))
    
  • + 0 comments

    Here is my Python solution!

    def beautifulTriplets(d, arr):
        beautiful = 0
        for i in range(len(arr) - 2):
            for j in range(i + 1, len(arr) - 1):
                if arr[j] - arr[i] == d:
                    for k in range(j + 1, len(arr)):
                        if arr[k] - arr[j] == d:
                            beautiful += 1
        return beautiful