Closest numbers from a list of unsorted integers

2.2

Given a list of distinct unsorted integers, find the pair of elements that have the smallest absolute difference between them? If there are multiple pairs, find them all.

Examples:

Input : arr[] = {10, 50, 12, 100}
Output : (10, 12)
The closest elements are 10 and 12

Input : arr[] = {5, 4, 3, 2}
Output : (2, 3), (3, 4), (4, 5)

This problem is mainly an extension of Find minimum difference between any two elements.

  1. Sort the given array.
  2. Find minimum difference of all pairs in linear time in sorted array.
  3. Traverse sorted array one more time to print all pairs with minimum difference obtained in step 2.

C++

// CPP program to find minimum difference
// an unsorted array.
#include<bits/stdc++.h>
using namespace std;

// Returns minimum difference between any
// two pair in arr[0..n-1]
void printMinDiffPairs(int arr[], int n)
{
   if (n <= 1)
      return;

   // Sort array elements
   sort(arr, arr+n);

   // Compare differences of adjacent
   // pairs to find the minimum difference.
   int minDiff = arr[1] - arr[0];
   for (int i = 2 ; i < n ; i++)
      minDiff = min(minDiff, arr[i] - arr[i-1]);

   // Traverse array again and print all pairs
   // with difference as minDiff.
   for (int i = 1; i < n; i++)
      if ((arr[i] - arr[i-1]) == minDiff)
         cout << "(" << arr[i-1] << ", "
              << arr[i] << "), ";
}

// Driver code
int main()
{
    int arr[] = {5, 3, 2, 4, 1};
    int n = sizeof(arr) / sizeof(arr[0]);
    printMinDiffPairs(arr, n);
    return 0;
}

Java

// Java program to find minimum 
// difference an unsorted array.
import java.util.*;

class GFG 
{
    
  // Returns minimum difference between 
  // any two pair in arr[0..n-1]
  static void printMinDiffPairs(int arr[], int n)
  {
    if (n <= 1)
      return;
    
    // Sort array elements
    Arrays.sort(arr);
    
    // Compare differences of adjacent
    // pairs to find the minimum difference.
    int minDiff = arr[1] - arr[0];
    for (int i = 2; i < n; i++)
      minDiff = Math.min(minDiff, arr[i] - arr[i-1]);
     
    // Traverse array again and print all pairs
    // with difference as minDiff.
    for ( int i = 1; i < n; i++)
     {
        if ((arr[i] - arr[i-1]) == minDiff)
        {
           System.out.print("(" + arr[i-1] + ", "
                           + arr[i] + ")," );
        }                    
     }
  }
    
  // Driver code
  public static void main (String[] args) 
  {
    int arr[] = {5, 3, 2, 4, 1};
    int n = arr.length;
    printMinDiffPairs(arr, n);
  }
}

// This code is contributed by Ansu Kumari

Python3

# Python3 program to find minimum 
# difference in an unsorted array.

# Returns minimum difference between
# any two pair in arr[0..n-1]
def printMinDiffPairs(arr , n):
    if n <= 1: return

    # Sort array elements
    arr.sort()
    
    # Compare differences of adjacent
    # pairs to find the minimum difference.
    minDiff = arr[1] - arr[0]
    for i in range(2 , n):
        minDiff = min(minDiff, arr[i] - arr[i-1])

    # Traverse array again and print all
    # pairs with difference as minDiff.
    for i in range(1 , n):
        if (arr[i] - arr[i-1]) == minDiff:
            print( "(" + str(arr[i-1]) + ", " 
                 + str(arr[i]) + "), ", end = '')

# Driver code
arr = [5, 3, 2, 4, 1]
n = len(arr)
printMinDiffPairs(arr , n)

# This code is contributed by Ansu Kumari


Output:

(1, 2), (2, 3), (3, 4), (4, 5), 

Does above program handle duplicates?
The cases like {x, x, x} are not handled by above program. For this case, the expected output (x, x), (x, x), (x, x), but above program prints (x, x), (x, x)


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

GATE CS Corner    Company Wise Coding Practice

Recommended Posts:



2.2 Average Difficulty : 2.2/5.0
Based on 4 vote(s)