Top MNC interview question which will be very useful for beginners to crack the interview and for there future careers

test

Breaking

Post Top Ad

Your Ad Spot

Wednesday, January 6, 2021

Google Interview Prep | Find all triplets with zero sum | Python

 Question:

Find all triplets with zero sum

Explanation:

We need to find all triplets of zero sum in the given array

For Example:

                       Array : arr[] = {0, -1, 2, -3, 1}
                       Result : (0 -1 1), (2 -3 1)
Program:

def Triplets(arr, n): 
  
    res = True
    for i in range(0, n-2): 
      
        for j in range(i+1, n-1): 
          
            for k in range(j+1, n): 
              
                if (arr[i] + arr[j] + arr[k] == 0): 
                    print(arr[i], arr[j], arr[k]) 
                    res = True
      


    if (res == False): 
        print(" not exist ")

 

arr = [0, -1, 2, -3, 1] 
n = len(arr) 
Triplets(arr, n) 

                                                                ---------End---------

Post Top Ad

Your Ad Spot