Two numbers with sum closest to zero

Last updated: 29th Aug, 2020

      

Problem Statment

Given an integer array A of N elements. You need to find the sum of two elements such that sum is closest to zero.



Example 1:

Input
3
3
-8 -66 -60
6
-21 -67 -37 -18 4 -65
2
-24 -73

Output:
-68
-14
-97

Method:

  • Sort the given array.
  • Then use the left and right pointers.
  • Calculate the sum of the left and right element of array.
  • Check if the sum is less then absolute value of previous sum
  • Update the previous sum.
  • If sum is less than zero the increase left pointer by one.
  • Otherwise,decrease right point by one.

Python Code

test=int(input())
for i in range(test):
    size=int(input())
    arr=list(map(int,input().split()))
    left=0
    right=size-1
    sum,minsum=0,10**9
    arr.sort()
    while(left< right):
        sum=arr[left]+arr[right]
        if(abs(sum)< abs(minsum)):
            minsum=sum
        if(sum< 0):
            left+=1
        else:
            right-=1
    print(minsum)