Closest Numbers:

Sorting is often useful as the first step in many different tasks. The most common task is to make finding things easier, but there are other uses, as well.

Challenge
Given a list of unsorted integers,A[a1,a2,a3............an], can you find the pair of elements that have the smallest absolute difference between them? If there are multiple pairs, find them all.

Input Format
The first line of input contains a single integer,N, representing the length of array.
In the second line, there are N space-separated integers, representing the elements of array.

Output Format
Output the pairs of elements with the smallest difference. If there are multiple pairs, output all of them in ascending order, all on the same line (consecutively) with just a single space between each pair of numbers. If there's a number which lies in two pair, print it two times (see the sample case #3 for explanation).

Sample Input #1

10
-20 -3916237 -357920 -3620601 7374819 -7330761 30 6246457 -6461594 266854

Sample Output #1

-20 30

Explanation
(30) - (-20) = 50, which is the smallest difference.

Sample Input #2

12
-20 -3916237 -357920 -3620601 7374819 -7330761 30 6246457 -6461594 266854 -520 -470

Sample Output #2

-520 -470 -20 30

Explanation
(-470) - (-520) = 30 - (-20) = 50, which is the smallest difference.

Sample Input #3

4
5 4 3 2

Sample Output #3

2 3 3 4 4 5

Explanation
Here, the minimum difference will be1. So valid pairs are(2, 3),(3, 4), and(4, 5). So we have to print_2_once,_3_and_4_twice each, and_5_once.

Solution:

  • They want minimum distance. If we sort the array then we just need to find diff between the consecutive numbers as they will be the lowest.
  • So sort the array, find the DIFF in consecutive elements and store it in a dictionary with key=DIFF and values = respective consecutive elements.
  • Then print the values having the minimum key.
# Enter your code here. Read input from STDIN. Print output to STDOUT
n = int(raw_input())
arr = map(int,raw_input().split())
arr = sorted(arr)
score = {}
for i in range(n-1):
    diff = abs(arr[i]-arr[i+1])
    if diff in score:
        score[diff].append(arr[i])
        score[diff].append(arr[i+1])
    else:
        score[diff] = [arr[i],arr[i+1]]

for ans in score[min(score.keys())]:
   print ans,

results matching ""

    No results matching ""