publicclassSolution {
publicintclosestSumToZero(int[] arr) {
Arrays.sort(arr);
int left = 0;
int right = arr.length- 1;
int closestSum = Integer.MAX_VALUE;
while (left < right) {
int currentSum = arr[left]+ arr[right];
if (Math.abs(currentSum) < Math.abs(closestSum)) {
closestSum = currentSum;
}
if (currentSum < 0) {
left++;
} else {
right--;
}
}
return closestSum;
}
publicstaticvoidmain(String[] args) {
Solution solution =new Solution();
int[] a1 = {1, 4, -5, 3, -2, 10, -6, 20};
System.out.println("Sum close to zero in the given array is: "+ solution.closestSumToZero(a1)); // Output: 1int[] a2 = {-5, 5, 8};
System.out.println("Sum close to zero in the given array is: "+ solution.closestSumToZero(a2)); // Output: 0int[] a3 = {5, 8};
System.out.println("Sum close to zero in the given array is: "+ solution.closestSumToZero(a3)); // Output: 13int[] a4 = {-5, -5, -8};
System.out.println("Sum close to zero in the given array is: "+ solution.closestSumToZero(a4)); // Output: -10 }
}
classSolution:
defclosestSumToZero(self, arr):
arr.sort()
left =0 right = len(arr) -1 closest_sum = float('inf')
closest_pair = (None, None)
while left < right:
current_sum = arr[left] + arr[right]
if abs(current_sum) < abs(closest_sum):
closest_sum = current_sum
closest_pair = (arr[left], arr[right])
if current_sum <0:
left +=1else:
right -=1return closest_sum
# Example usagesolution = Solution()
a1 = [1, 4, -5, 3, -2, 10, -6, 20]
print(f"Sum close to zero in the given array is : {solution.closestSumToZero(a1)}") # Output: 1a2 = [-5, 5, 8]
print(f"Sum close to zero in the given array is : {solution.closestSumToZero(a2)}") # Output: 0a3 = [5, 8]
print(f"Sum close to zero in the given array is : {solution.closestSumToZero(a3)}") # Output: 13a4 = [-5, -5, -8]
print(f"Sum close to zero in the given array is : {solution.closestSumToZero(a4)}") # Output: -10
⏰ Time complexity: O(n log n) - O(n log n) for sorting the array, and O(n) for the two-pointer traversal, resulting in an overall complexity of O(n log n).
🧺 Space complexity: O(1), as the algorithm uses a constant amount of extra space.