|
| 1 | +''' |
| 2 | + Author : Mohit Kumar |
| 3 | + |
| 4 | + Python program to find triplets in a given array whose sum is zero |
| 5 | +''' |
| 6 | + |
| 7 | +# function to print triplets with 0 sum |
| 8 | +def find_Triplets_with_zero_sum(arr, num): |
| 9 | + |
| 10 | + ''' find triplets in a given array whose sum is zero |
| 11 | + |
| 12 | + Parameteres : |
| 13 | + arr : input array |
| 14 | + num = size of input array |
| 15 | + Output : |
| 16 | + if triplets found return their values |
| 17 | + else return "No Triplet Found" |
| 18 | + ''' |
| 19 | + # bool variable to check if triplet found or not |
| 20 | + found = False |
| 21 | + |
| 22 | + # sort array elements |
| 23 | + arr.sort() |
| 24 | + |
| 25 | + # Run a loop until l is less than r, if the sum of array[l], array[r] is equal to zero then print the triplet and break the loop |
| 26 | + for index in range(0, num - 1) : |
| 27 | + |
| 28 | + # initialize left and right |
| 29 | + left = index + 1 |
| 30 | + right = num - 1 |
| 31 | + |
| 32 | + curr = arr[index] # current element |
| 33 | + |
| 34 | + while (left < right): |
| 35 | + |
| 36 | + temp = curr + arr[left] + arr[right] |
| 37 | + |
| 38 | + if (temp == 0) : |
| 39 | + # print elements if it's sum is zero |
| 40 | + print(curr, arr[left], arr[right]) |
| 41 | + |
| 42 | + left += 1 |
| 43 | + right -= 1 |
| 44 | + |
| 45 | + found = True |
| 46 | + |
| 47 | + |
| 48 | + # If sum of three elements is less than zero then increment in left |
| 49 | + elif (temp < 0) : |
| 50 | + left += 1 |
| 51 | + |
| 52 | + # if sum is greater than zero than decrement in right side |
| 53 | + else: |
| 54 | + right -= 1 |
| 55 | + |
| 56 | + if (found == False): |
| 57 | + print(" No Triplet Found") |
| 58 | + |
| 59 | +# DRIVER CODE STARTS |
| 60 | + |
| 61 | +if __name__ == "__main__": |
| 62 | + |
| 63 | + n = int(input('Enter size of array\n')) |
| 64 | + print('Enter elements of array\n') |
| 65 | + |
| 66 | + arr = list(map(int,input().split())) |
| 67 | + |
| 68 | + print('Triplets with 0 sum are as : ') |
| 69 | + |
| 70 | + find_Triplets_with_zero_sum(arr, n) |
| 71 | + |
| 72 | +''' |
| 73 | +SAMPLE INPUT 1 : |
| 74 | + Enter size of array : 5 |
| 75 | + Enter elements of array : 0, -1, 2, -3, 1 |
| 76 | +OUTPUT : |
| 77 | + Triplets with 0 sum are as : |
| 78 | + -3 1 2 |
| 79 | + -1 0 1 |
| 80 | +COMPLEXITY ANALYSIS : |
| 81 | +Time Complexity : O(n^2). |
| 82 | + Only two nested loops is required, so the time complexity is O(n^2). |
| 83 | +Auxiliary Space : O(1), no extra space is required, so the time complexity is constant. |
| 84 | +''' |
0 commit comments