# Closest Numbers – HackerRank Solution

In this post, we will solve Closest Numbers HackerRank Solution. This problem (Closest Numbers) is a part of HackerRank Problem Solving series.

## Solution – Closest Numbers – HackerRank Solution

### C++

```#include<iostream>
#include<algorithm>
#include<climits>
#include<vector>
using namespace std;

int a[200000];

vector<int> ansv;

int main()
{
int n;
cin >> n;
for (int i = 0; i < n; i++)
cin >> a[i];
sort(a, a + n);
int ans = INT_MAX;
for (int i = 1; i < n; i++)
{
if (a[i] - a[i - 1] < ans)
{
ansv.clear();
ans = a[i] - a[i - 1];
ansv.push_back(a[i - 1]);
ansv.push_back(a[i]);
}
else if (a[i] - a[i - 1] == ans)
{
ansv.push_back(a[i - 1]);
ansv.push_back(a[i]);
}
}
for (int i = 0; i < (int)ansv.size(); i++)
cout << ansv[i] << " ";
cout << endl;
return 0;
}
```

### Python

```#!/bin/python3

import sys

def closestNumbers(arr):
output = []
arr = sorted(arr)
nowmin = 10**9

for ind in range(1, len(arr)):
diff = abs(arr[ind-1] - arr[ind])

if diff < nowmin:
output = [(arr[ind-1], arr[ind])]
nowmin = diff
elif diff == nowmin:
output.append((arr[ind-1], arr[ind]))

flat_list = [item for sublist in output for item in sublist]

return flat_list

if __name__ == "__main__":
n = int(input().strip())
arr = list(map(int, input().strip().split(' ')))
result = closestNumbers(arr)
print (" ".join(map(str, result)))

```

### Java

```import java.io.*;
import java.util.*;

public class Solution {

public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int[] array = new int[n];
for(int i = 0; i < n; i++)
array[i] = input.nextInt();

Arrays.sort(array);
int minAbs = Integer.MAX_VALUE; //Minimum absolute difference
StringBuilder pairs = new StringBuilder("");

for(int i = 0; i < n-1; i++)
{
int absDiff;

if((array[i]<0 && array[i+1]<0)||(array[i]>0 && array[i+1]>0))//both numbers have matching signs
absDiff = Math.abs(array[i] - array[i+1]); //Absolute difference
else
absDiff = Math.abs(array[i]) + Math.abs(array[i+1]); //Absolute difference

if(absDiff < minAbs)//New minAbs
{
minAbs = absDiff;
pairs = new StringBuilder("");//Empty pairs
pairs.append(array[i]+ " " +array[i+1]+" ");//Add pair
}
else if(absDiff == minAbs)//Multiple minAbs
pairs.append(array[i]+ " " +array[i+1]+" ");//Add pair
}

System.out.println(pairs);
}
}
```

Note: This problem (Closest Numbers) is generated by HackerRank but the solution is provided by CodingBroz. This tutorial is only for Educational and Learning purpose.