We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
n=int(input())a=sorted(map(int,input().split()))n=len(a)# For one incorrect test casediff=[(i,a[i+1]-a[i])foriinrange(n-1)]diff.sort(key=lambdax:x[1])a1=[]fordiindiff:ifdi[1]!=diff[0][1]:breakelse:a1.append(a[di[0]])a1.append(a[di[0]+1])print(*a1)
Sort the input array
Calculate the difference of adjacent elements and store it with its index as (i, a[i+1] - a[i]) in difference array
Sort this difference array on the basis of the second element of the tuple i.e. the difference
Iterate over this sorted difference array and print array elements for those tuples whose difference is same as difference of first tuple i.e. minimum difference
Break the iteration if the current difference in the tuple does not match the difference in the first tuple i.e. minimum difference.
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Closest Numbers
You are viewing a single comment's thread. Return to all comments →
Sort the input array
Calculate the difference of adjacent elements and store it with its index as (i, a[i+1] - a[i]) in difference array
Sort this difference array on the basis of the second element of the tuple i.e. the difference
Iterate over this sorted difference array and print array elements for those tuples whose difference is same as difference of first tuple i.e. minimum difference
Break the iteration if the current difference in the tuple does not match the difference in the first tuple i.e. minimum difference.