Closest Numbers

  • + 0 comments

    Solution using dictionary

    def closestNumbers(arr):
        # Write your code 
        arr.sort()
        result = {}
        for index in range(len(arr)):
            if (index +1 < len(arr)):
                current_dif = abs(arr[index] - arr[index + 1])
                if (current_dif in result):
                    result[current_dif].append((arr[index], arr[index + 1]))
                else:
                    result[current_dif] = [(arr[index], arr[index + 1])]
        
        min_key = min(list(result.keys()))
        arr_result = result[min_key]
        final_result = []
        for item in arr_result:
            final_result.extend(item)
        return final_result