In this Hackerrank Closest Numbers problem, we have given a list of unsorted integers, we need to find the pair of elements that have the smallest absolute difference between them. and if there are multiple elements then find them all and print them.

hackerrank Closest numbers problem solution


Problem solution in Python programming.

#!/usr/bin/env python3

N = int(input())
arr = [int(x) for x in input().split()]
arr.sort()

result = []
diff = 2**31-1
for i in range(1, len(arr)):
    if arr[i] - arr[i-1] <= diff:
        if arr[i] - arr[i-1] < diff:
            diff = arr[i] - arr[i-1]
            result = []
        result.append(arr[i])
        result.append(arr[i-1])

print(' '.join([str(x) for x in sorted(result)]))


Problem solution in Java Programming.

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

public class Solution {

    public static void main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();
        int[] a = new int[N];
        for(int i = 0; i < N; i++){
            a[i] = sc.nextInt();
        }
        Arrays.sort(a);
        int min = Integer.MAX_VALUE;
        for(int i = 0 ; i< N-1; i++){
            min = Math.min(min, a[i+1] - a[i]);
        }
        StringBuilder sb = new StringBuilder("");
        for(int i = 0; i < N-1; i++){
            if(a[i+1] - a[i] == min){
                sb.append(a[i] + " " + a[i+1] + " ");
            }
        }
        System.out.println(sb.toString());
     }
}


Problem solution in C++ programming.

#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <tuple>
#include <array>
#include <limits>
#include <algorithm>

using namespace std;

int main() {
  int n;
  cin >> n;
  vector<pair<int, int>> values(n, {0, 0});
  for (auto& p: values) {
    cin >> p.first;
    p.second = p.first;
  }
  sort(values.begin(), values.end());
  for (size_t i = 1; i < values.size(); ++i) {
    values[i-1].first = values[i-1].second - values[i].second;
  }
  sort(values.begin(), values.end(),
      [](const pair<int, int>& p1, const pair<int, int>& p2) {
      return abs(p1.first) < abs(p2.first);
  });
  auto it = values.begin();
  int best = abs(it->first);
  vector<int> best_values;
  while (abs(it->first) == best) {
    best_values.push_back(it->second);
    best_values.push_back(it->second - it->first);
    ++it;
  }
  sort(best_values.begin(), best_values.end());
  for (auto it = best_values.begin(), end = best_values.end(); it != end; ++it) {
    if (it != best_values.begin()) {
      cout << " ";
    }
    cout << *it;
  }
  cout << endl;
}


Problem solution in C programming.

#include<stdio.h>
#include<stdlib.h>

void quickSort(int[], int, int);
int partition(int[], int, int);


int main(){
	
	int i,n;
	
	//input
	scanf("%d",&n);
	int *a=(int *)malloc(n*sizeof(int));
	
	for(i=0;i<n;i++)
		scanf("%d",&a[i]);

	//sorting
	quickSort(a,0,n-1);
	
	
	//finding smallest
	int min=a[1]-a[0];
	for(i=2;i<n;i++)
		if(a[i]-a[i-1]<min) min=a[i]-a[i-1];
	
	//printing all pairs
	for(i=1;i<n;i++)
		if(a[i]-a[i-1]==min) printf("%d %d ",a[i-1],a[i]);
	printf("\n");

return 0;
}



void quickSort(int a[], int l, int r)
{
   int j;

   if( l < r ) 
   {
   	// divide and conquer
        j = partition( a, l, r);
       quickSort( a, l, j-1);
       quickSort( a, j+1, r);
   }
	
}


int partition(int a[], int l, int r) {
   int pivot, i, j, t;
   pivot = a[l];
   i = l; j = r+1;
		
   while( 1)
   {
   	//for ascending part, erase the line below and use instead those inside the comments: .
   	do ++i; while( a[i] <= pivot && i <= r );
   	do --j; while( a[j] > pivot ); 
   	/*do ++i; while( a[i] >= pivot && i <= r );
   	do --j; while( a[j] < pivot );*/
   	if( i >= j ) break;
   	t = a[i]; a[i] = a[j]; a[j] = t;
   }
   t = a[l]; a[l] = a[j]; a[j] = t;
   return j;
}


Problem solution in JavaScript programming.

function processData(input) {
    input.sort(function (a, b) {
        return a - b;
    });
    
    var max = input[1] - input[0];
    var maxPairs = [input[0], input[1]];
    
    for (var i = 2; i < input.length; i++) {
        var prev = input[i - 1];
        var next = input[i];
        var diff = next - prev;
        
        if (diff < max) {
            max = diff;
            maxPairs = [prev, next];
        } else if (diff === max) {
            maxPairs = maxPairs.concat([prev, next]);
        }
    }
    
    console.log(maxPairs.join(' '));
} 

process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
    _input += input;
});

process.stdin.on("end", function () {
    var array = String(_input.split('\n').slice(1)).split(' ').map(function(number) { return Number(number); });
    processData(array);
});