In this post, we will solve HackerRank Closest Numbers Problem Solution.
Sorting is 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. In this case, it will make it easier to determine which pair or pairs of elements have the smallest absolute difference between them.
Example
arr = [5, 2, 3, 4, 1]
Sorted, arr’ = [1, 2, 3, 4, 5]. Several pairs have the minimum difference of 1:
[(1, 2), (2, 3), (3, 4), (4, 5)]. Return the array [1, 2, 2, 3, 3, 4, 4, 5].
Note
As shown in the example, pairs may overlap.
Given a list of unsorted integers, arr, find the pair of elements that have the smallest absolute difference between them. If there are multiple pairs, find them all.
Function Description
Complete the closestNumbers function in the editor below.
closestNumbers has the following parameter(s):
- int arr[n]: an array of integers
Returns
– int[]: an array of integers as described
Input Format
The first line contains a single integer n. the length of arr.
The second line contains n space-separated integers, arr[i].
Output Format
Sample Input 0
10
-20 -3916237 -357920 -3620601 7374819 -7330761 30 6246457 -6461594 266854
Sample Output 0
-20 30
Explanation 0
(30) – (-20) = 50, which is the smallest difference.
Sample Input 1
12
-20 -3916237 -357920 -3620601 7374819 -7330761 30 6246457 -6461594 266854 -520 -470
Sample Output 1
-520 -470 -20 30
Explanation 1
(-470) – (-520) = 30 – (-20) = 50, which is the smallest difference.
Sample Input 2
4
5 4 3 2
Sample Output 2
2 3 3 4 4 5
Explanation 2
Here, the minimum difference is 1. Valid pairs are (2, 3), (3, 4), and (4, 5).

Closest Numbers C Solution
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
long int cmpfunc (const void * a, const void * b)
{
return ( *(long int*)a - *(long int*)b );
}
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int n,i=0;
long int a[200000],diff,small=100000000;
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%ld",&a[i]);
qsort(a,n,sizeof(long int),cmpfunc);
for(i=1;i<n;i++)
{
diff = a[i]-a[i-1];
if(diff<0)
diff*=-1;
if(diff<small)
{
small = diff;
}
}
for(i=1;i<n;i++)
{
diff = a[i]-a[i-1];
if(diff<0)
diff*=-1;
if(diff==small)
printf("%ld %ld ",a[i-1],a[i]);
}
return 0;
}
Closest Numbers C++ Solution
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
int n, a[200005];
int main() {
scanf("%d",&n);
for(int i=0;i<n;i++) scanf("%d",&a[i]);
std::sort(a,a+n);
int diff = 2e9;
for(int i=0;i+1<n;i++) diff = std::min(diff, a[i+1]-a[i]);
for(int i=0;i+1<n;i++) if(a[i+1]-a[i]==diff) printf("%d %d ",a[i],a[i+1]);
return 0;
}
Closest Numbers C Sharp Solution
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
class Solution {
const int MAX = 20000002;
static int[] bit = new int[MAX];
static bool[] flag = new bool[MAX];
static int min = MAX;
static List<KeyValuePair<int, int>> L;
static void add_bit(int n)
{
int max = n;
flag[n] = true;
n += n & -n;
while (n < MAX && bit[n] < max)
{
bit[n] = max;
n += n & -n;
}
}
static void find_pair(int n)
{
int diff = 0, N = n, k = 0;
while (n > 0)
{
if (n != N && flag[n])
{
diff = N - n;
k = n;
break;
}
if (bit[n] > 0)
{
diff = N - bit[n];
k = bit[n];
break;
}
n -= n & -n;
}
if (diff > 0)
{
if (diff < min)
{
min = diff;
L = new List<KeyValuePair<int, int>>();
L.Add(new KeyValuePair<int, int>(k - 10000001, N - 10000001));
}
else if (diff == min)
{
L.Add(new KeyValuePair<int, int>(k - 10000001, N - 10000001));
}
}
}
static void Main(String[] args)
{
int N = int.Parse(Console.ReadLine());
string[] s = Console.ReadLine().Split();
int[] a = new int[N];
for (int i = 0; i < N; i++)
{
a[i] = int.Parse(s[i]) + 10000001;
}
for (int i = 0; i < N; i++)
{
add_bit(a[i]);
}
for (int i = 0; i < N; i++)
{
find_pair(a[i]);
}
int length = L.Count;
L = L.OrderBy(x => x.Key).ToList();
for (int i = 0; i < length; i++)
{
Console.Write(L[i].Key + " ");
Console.Write(L[i].Value + " ");
}
}
}
Closest Numbers Java Solution
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
class Result {
/*
* Complete the 'closestNumbers' function below.
*
* The function is expected to return an INTEGER_ARRAY.
* The function accepts INTEGER_ARRAY arr as parameter.
*/
public static List<Integer> closestNumbers(List<Integer> arr) {
// Write your code here
// Write your code here
Collections.sort(arr);
Map<Integer, List<Integer>> map = new TreeMap<>();
for (int i = 1; i < arr.size(); i++) {
map.computeIfAbsent(arr.get(i) - arr.get(i - 1), k -> new ArrayList<>())
.add(i);
}
List<Integer> ans = new ArrayList<>();
if (!map.isEmpty()) {
List<Integer> ps = map.values()
.iterator()
.next();
for (Integer p : ps) {
ans.add(arr.get(p - 1));
ans.add(arr.get(p));
}
}
return ans;
}
}
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
int n = Integer.parseInt(bufferedReader.readLine().trim());
List<Integer> arr = Stream.of(bufferedReader.readLine().replaceAll("\\s+$", "").split(" "))
.map(Integer::parseInt)
.collect(toList());
List<Integer> result = Result.closestNumbers(arr);
bufferedWriter.write(
result.stream()
.map(Object::toString)
.collect(joining(" "))
+ "\n"
);
bufferedReader.close();
bufferedWriter.close();
}
}
Closest Numbers JavaScript Solution
function processData(input) {
//Enter your code here
var lines = input.split("\n");
var N = lines[0];
var nums = lines[1].split(" ");
nums.sort(function(a,b){return a-b});
var result = "";
var maxdiff = Infinity;
for (var i=1;i<nums.length;i++) {
if ((nums[i]-nums[i-1]) < maxdiff) {
maxdiff = nums[i]-nums[i-1];
result = nums[i-1] + " " + nums[i];
} else if ((nums[i]-nums[i-1]) == maxdiff) {
result += " " + nums[i-1] + " " + nums[i];
}
}
console.log(result);
}
process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
_input += input;
});
process.stdin.on("end", function () {
processData(_input);
});
Closest Numbers Python Solution
n = int(input())
array = list(map(int,input().split()))
array.sort()
min_diff = min(array[i+1]-array[i] for i in range(len(array)-1))
print(' '.join(str(array[i])+' '+str(array[i+1]) for i in range(len(array)-1) if array[i+1]-array[i] == min_diff))
Other Solutions