Closest Numbers

  • + 0 comments

    Python 3 solution:

    from itertools import pairwise
    
    
    def closestNumbers(arr: list[int]) -> list[int]:
        pairs = []
        min_diff = float("inf")
        arr.sort()
        for i, j in pairwise(arr):
            if (diff := abs(i - j)) == min_diff:
                pairs += [i, j]
                continue
            if diff < min_diff:
                min_diff = diff
                pairs = [i, j]
        return pairs