Can someone please help me with the optimal solution for this?

Viewed 23

Given a stream of numbers, find triplets such that every pair in the triplet have difference of at most 7

example -> 22,3,1,8,10,6,13.... output -> [(3,6,8),(8,10,13),(6,13,8),(3,1,8),(3,1,6),(3,8,10),(3,10,6),(1,8,6),(6,8,10),(10,6,13)]

Please help me find the optimal approach for this

Tried naive solution where I stored the elements in a list then passed that list everytime to the helper function

def triplets(arr, targ):


    def helper(a,targ,res):
       if len(a)>=3:
         for i in range(len(a)-2):
            for j in range(i+1,len(a)-1):
                for k in range(j+1,len(a)):

                    if abs(arr[j]-arr[k])<=targ and abs(arr[i]-arr[k])<=targ and abs(arr[i]-arr[j])<=targ:
                        res.append((arr[i],arr[j],arr[k]))

      res=[]
      helper(arr,targ,res)
      #print(res)
      triplets(arr, targ)
0 Answers
Related