
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Two Elements Whose Sum is Closest to Zero in Java
In this article we will learn how to find the two elements in an array whose sum is closest to zero. The array can contain both positive and negative values as well. Let's understand with the help of an example.
Example
Let's take an array with the following elements ?
arr = {3, -56, -76, -32, 45, 77, -14, 13, 92, 37}
Here, two elements whose sum is closest to zero are 77 and -76, and their sum is 1.
Note: In this example we have 77 and -76, which will give the sum as 1, and also we have -14 and 13, which will give the sum as -1. In that case we will always take the positive number.
We can solve this problem using two approaches ?
- Brute force approach
- Two-pointer approach
Brute force approach
In this brute force method, we will check through all possible pairs in the array and calculate their sum to see which pairs have their sum closest to zero. We will also use a variable to store the minimum sum and compare it with the sum after each calculation. This brute force solution is simple to execute but is not very efficient.
Steps for implementation
The following steps break down the logic of finding the closest sum using a simple approach.
Step 1: Declare a variable named minSum and initialize it with the maximum integer value in the beginning.
Step 2: Use two nested for-loops to find all possible pairs in the array.
Step 3: In each iteration, calculate the sum of the pairs and check if it's closer to zero than the previously stored minSum value.
Step 4: If yes, update minSum and store the two elements.
Step 5: Finally, after all the iterations, print the minSum and the two elements.
Implementation code
Below is the Java program that implements the brute force approach to find two elements whose sum is closest to zero.
import java.util.Arrays; public class sumclose2zero{ public static void findElementsClosestToZero(int[] arr){ if(arr.length<2){ System.out.println("Array should have at least two elements."); return; } int minSum=Integer.MAX_VALUE,element1=0,element2=0; for(int i=0;i<arr.length-1;i++){ for(int j=i+1;j<arr.length;j++){ int sum=arr[i]+arr[j]; if(Math.abs(sum)<Math.abs(minSum)){ minSum=sum; element1=arr[i]; element2=arr[j]; } } } System.out.println("The two elements whose sum is closest to zero are: "+element1+" and "+element2); System.out.println("Their sum is: "+minSum); } public static void main(String[] args){ int[] arr= {7,-24,31,22,28,19,94,25,32,34,12}; findElementsClosestToZero(arr); } }
Output
The two elements whose sum is closest to zero are: -24 and 25 Their sum is: 1
Time complexity
This approach has the time complexity of O(n²), as it uses two for-loops to check each and every pair. The time increases quadratically with the input, which means this approach is very slow and not efficient for large datasets.
Two-pointer approach
The two-pointer approach is the most efficient way for solving this problem. Instead of checking each and every pair in the array, we first sort the array and use two pointers, one starting from the left end and the other from the right end of the array, to calculate the sum.
- If the sum of the two numbers is negative, it means we need a larger value to get close to zero. Since the array is sorted, we will move the left pointer forward to fetch the next larger element.
- If the sum is positive, we need a smaller value to reach closer to zero. So we move the right pointer backward, which will help us to fetch the next smaller element.
After calculating each sum, we compare it with the minSum value and update it if it is smaller than the minSum value, which means it's closer to zero.
Steps for implementation
These steps explain how to use the two-pointer technique to efficiently find the closest sum.
Step 1: Sort the array.
Step 2: Initialize the left and right pointers. Also initialize a minSum variable to store the minimum absolute sum.
Step 3: Now traverse the array using the two pointers and calculate their sum.
Step 4: Update the minSum if the new sum is closer to zero.
Step 5: If the sum is negative, move the left pointer forwards; otherwise, move the right pointer backwards.
Step 6: After traversing the whole array, print the minSum.
Implementation code
Below is the Java program that implements the two-pointer approach efficiently.
import java.util.Arrays; public class sumclose2zero{ public static void findElementsClosestToZero(int[] arr){ if(arr.length<2){ System.out.println("Array should have at least two elements."); return; } Arrays.sort(arr); int left=0,right=arr.length-1,minSum=Integer.MAX_VALUE,minLeft=left,minRight=right; while(left<right){ int sum=arr[left]+arr[right]; if(Math.abs(sum)<Math.abs(minSum)){ minSum=sum; minLeft=left; minRight=right; } if(sum<0) left++; else right--; } System.out.println("The two elements whose sum is closest to zero are: "+arr[minLeft]+" and "+arr[minRight]); System.out.println("Their sum is: "+minSum); } public static void main(String[] args){ int[] arr={6,36,-9,45,32,-43,-87,56,19,43}; findElementsClosestToZero(arr); } }
Output
The two elements whose sum is closest to zero are: -43 and 43 Their sum is: 0
Time complexity
Sorting the array takes O(nlogn) time, and two-pointer traversing takes O(n) time complexity. So the total time complexity will be O(nlogn). This approach is way faster than the brute force approach.