Find a Pair Whose Sum is Closest to zero in Array

If you want to practice data structure and algorithm programs, you can go through data structure and algorithm interview questions.

Problem :

Given array of +ve and -ve integers ,we need to find a pair whose sum is closed to Zero in Array.
For example:

Solution :

Solution 1:

You can check each and every pair of numbers and find minimum sum.
Java code:

 Solution 2:

  • Sort the array.
  • We will maintain two indexes one at beginning (l=0) and one at end (r=n-1)
  • iterate until l <  r
  • Calculate sum of arr[l] + arr[r]
  • if abs (sum) < abs (minSum), then update the minimum sum and pair.
  • If sum is less than 0, this means if we want to find sum close to 0, do r–
  • If sum is greater than 0,this means if we want to find sum close to 0 , do l++
Java code:

Time complexity : O(NLogN)

Java program to find a pair whose sum is closest to zero:

When you run the program, you will get below output:

Add Comment