I have created a program which that takes as input an array of positive and negative numbers (0 excluded) and return those items from the array whose sum is 0. If no such items exist return, then return “No Elements found”. Here I have written separate functions for twoSum, threeSUM, fourSum... but I want to have general function which will check for nSum (n is the number of elements of array)
e.g. In this list [-4, -3, -2, -1, 10], it should return -4, -3, -2, -1 and 10 there are 5 elements whose sum is 0. I am sharing my code. I have written in Python, but code in C/C++ is also welcomed. So please help.
What I have tried:
```
def twoSum(arr,n,x,lp,rp):
while lp<rp:
if arr[lp] + arr[rp] == x:
return True,arr[lp],arr[rp]
elif arr[lp] + arr[rp] < x:
lp+=1
else:
rp-=1
return False,0,0
def threeSum(arr,n,x,firstIndex):
for i in range(firstIndex,n-2):
check,a,b = twoSum(arr,n,x-arr[i],i+1,n-1)
if check:
return True,arr[i],a,b
return False,0,0,0
def finding_numbers(arr, n):
if arr[0]<0:
check,a,b = twoSum(arr,n,0,0,n-1)
if check:
return a,b
check,a,b,c = threeSum(arr,n,0,0)
if check:
return a,b,c
for i in range(n-3):
check,a,b,c = threeSum(arr,n,-arr[i],i+1)
if check:
return arr[i],a,b,c
return 'No Elements found'
finding_numbers(array, n)
```