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.
Python 3 - there are more efficient approaches instead of hash table for this specific problem though:
defclosestNumbers(arr):# Sort the arrayarr=sorted(arr)# Create a dictionary to store absolute differencesdifference_dict={}foriinrange(len(arr)-1):difference=abs(arr[i]-arr[i+1])# Store pairs for each unique differenceifdifferencenotindifference_dict:difference_dict[difference]=[]difference_dict[difference].append((arr[i],arr[i+1]))#Storeastuples# Find the minimum absolute differencemin_difference=min(difference_dict.keys())# Get the pairs corresponding to the minimum differenceclosest_pairs=difference_dict[min_difference]# Flatten the closest pairs into a listresult=[numforpairinclosest_pairsfornuminpair]returnlist(set(result))
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 →
Python 3 - there are more efficient approaches instead of hash table for this specific problem though: