Closest Numbers

  • + 0 comments

    Python 3 - there are more efficient approaches instead of hash table for this specific problem though:

    def closestNumbers(arr):
        # Sort the array
        arr = sorted(arr)
    
        # Create a dictionary to store absolute differences
        difference_dict = {}
        for i in range(len(arr) - 1):
            difference = abs(arr[i] - arr[i + 1])
            # Store pairs for each unique difference
            if difference not in difference_dict:
                difference_dict[difference] = []
            difference_dict[difference].append((arr[i], arr[i + 1]))  # Store as tuples
    
        # Find the minimum absolute difference
        min_difference = min(difference_dict.keys())
    
        # Get the pairs corresponding to the minimum difference
        closest_pairs = difference_dict[min_difference]
    
        # Flatten the closest pairs into a list
        result = [num for pair in closest_pairs for num in pair]
    
        return list(set(result))