How to find the two elements in a list whose sum is closest to zero in Python

1 Answer

0 votes
import sys

def find_closest_to_zero(lst):
    if len(lst) < 2:
        print("list must have at least two elements.")
        return

    # Step 1: Sort the list
    sorted_lst = sorted(lst)

    left = 0
    right = len(sorted_lst) - 1
    closest_sum = sys.maxsize  # Equivalent to INT_MAX
    closest_pair = [0, 0]

    # Step 2: Use two-indexed technique
    while left < right:
        sum_ = sorted_lst[left] + sorted_lst[right]

        # Update closest sum and pair if needed
        if abs(sum_) < abs(closest_sum):
            closest_sum = sum_
            closest_pair[0] = sorted_lst[left]
            closest_pair[1] = sorted_lst[right]

        # Move indexeds
        if sum_ < 0:
            left += 1  # Increase sum by moving left indexed
        else:
            right -= 1  # Decrease sum by moving right indexed

    # Output the result
    print(f"The two elements whose sum is closest to zero are: "
          f"{closest_pair[0]} and {closest_pair[1]} with a sum of {closest_sum}.")


lst = [23, -26, -88, -42, 55, 99, -11, 90, -13, 17, -31]

find_closest_to_zero(lst)




'''
run:

The two elements whose sum is closest to zero are: -88 and 90 with a sum of 2.

'''

 



answered Sep 13 by avibootz
edited Sep 13 by avibootz
...