Closest Numbers


Problem Statement :


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.


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].



Solution :



title-img


                            Solution in C :

In  C++  :







#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;


int main() {
  
    int n;
    std::cin>>n;
    std::vector<int>x;
    int tmp;
    int i;
    for(i = 0; i<n; i++)
    {
        std::cin>>tmp;
        x.push_back(tmp);
        
    }
    std::sort(x.begin(),x.end());
                   
    int diff = std::numeric_limits<int>::max();
    int currentDiff = 0;
    std::vector<int> start;
    std::vector<int> end;
    for(i = 0; i<n-1; i++)
    {
        currentDiff = x[i+1] - x[i];
        if(currentDiff<diff)
        {
            diff=currentDiff;
            while(!start.empty())
            {
                start.pop_back();
                end.pop_back();
            }
            start.push_back(x[i]);
            end.push_back(x[i+1]);
        }
        else if(currentDiff==diff)
        {
            start.push_back(x[i]);
            end.push_back(x[i+1]);
                
        }
        
        
    }
    
    for(i = 0; i<start.size(); i++)
    {
        std::cout<<start[i]<<" "<<end[i]<<" ";
    }
    return 0;
}









In   Java :






import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int[] dat = new int[n];
        for(int i = 0; i < n; i++) {
            dat[i] = in.nextInt();
        }
        Arrays.sort(dat);
        int minDiff = Integer.MAX_VALUE;
        String out = "";
        for(int i = 0; i < n - 1; i++) {
            if(dat[i + 1] - dat[i] <= minDiff) {
                if(dat[i + 1] - dat[i] == minDiff) {
                    out += " " + dat[i] + " " + dat[i + 1];
                } else {
                    out = dat[i] + " " + dat[i + 1];
                }
                minDiff = dat[i + 1] - dat[i];
            }
        }
        System.out.println(out);
    }
}







In   C  :







#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#define ll long long int

int compare(const void *a,const void *b)
{
  return (*(ll*)a-*(ll*)b);
}


int main() 
{
    ll n,i,a[200005],min;
    scanf("%lld",&n);
    for(i=0;i<n;i++)
    {
        scanf("%lld",&a[i]);
    }
    qsort(a,n,sizeof(ll),compare);
    min=10000000;
    for(i=0;i<n-1;i++)
    {
        if((a[i+1]-a[i])<min)
        {
            min=a[i+1]-a[i];
        }
    }
    for(i=0;i<n-1;i++)
    {
        if((a[i+1]-a[i])==min)
        {
            printf("%lld %lld ",a[i],a[i+1]);
        }
    }
    return 0;
}









In   Python3 :







def main():
    N = int(input())
    ar = sorted(list(map(int, str(input()).split())))
    prs = ''
    mini = pow(10, 7) + 1
    for i in range(1, N):
        diff = abs(ar[i-1] - ar[i])
        if (diff <= mini):
            if (diff < mini):
                prs = ''
            mini = diff
            prs += str(ar[i-1]) + ' ' + str(ar[i]) + ' '
    print (prs)

if __name__ == '__main__':
    main()
                        








View More Similar Problems

No Prefix Set

There is a given list of strings where each string contains only lowercase letters from a - j, inclusive. The set of strings is said to be a GOOD SET if no string is a prefix of another string. In this case, print GOOD SET. Otherwise, print BAD SET on the first line followed by the string being checked. Note If two strings are identical, they are prefixes of each other. Function Descriptio

View Solution →

Cube Summation

You are given a 3-D Matrix in which each block contains 0 initially. The first block is defined by the coordinate (1,1,1) and the last block is defined by the coordinate (N,N,N). There are two types of queries. UPDATE x y z W updates the value of block (x,y,z) to W. QUERY x1 y1 z1 x2 y2 z2 calculates the sum of the value of blocks whose x coordinate is between x1 and x2 (inclusive), y coor

View Solution →

Direct Connections

Enter-View ( EV ) is a linear, street-like country. By linear, we mean all the cities of the country are placed on a single straight line - the x -axis. Thus every city's position can be defined by a single coordinate, xi, the distance from the left borderline of the country. You can treat all cities as single points. Unfortunately, the dictator of telecommunication of EV (Mr. S. Treat Jr.) do

View Solution →

Subsequence Weighting

A subsequence of a sequence is a sequence which is obtained by deleting zero or more elements from the sequence. You are given a sequence A in which every element is a pair of integers i.e A = [(a1, w1), (a2, w2),..., (aN, wN)]. For a subseqence B = [(b1, v1), (b2, v2), ...., (bM, vM)] of the given sequence : We call it increasing if for every i (1 <= i < M ) , bi < bi+1. Weight(B) =

View Solution →

Kindergarten Adventures

Meera teaches a class of n students, and every day in her classroom is an adventure. Today is drawing day! The students are sitting around a round table, and they are numbered from 1 to n in the clockwise direction. This means that the students are numbered 1, 2, 3, . . . , n-1, n, and students 1 and n are sitting next to each other. After letting the students draw for a certain period of ti

View Solution →

Mr. X and His Shots

A cricket match is going to be held. The field is represented by a 1D plane. A cricketer, Mr. X has N favorite shots. Each shot has a particular range. The range of the ith shot is from Ai to Bi. That means his favorite shot can be anywhere in this range. Each player on the opposite team can field only in a particular range. Player i can field from Ci to Di. You are given the N favorite shots of M

View Solution →