Find minimum difference between any two elements | Set 2

09 Nov, 2021
Given an unsorted array arr[] of size n, the task is to find the minimum difference between any pair in the given array. 
Input: arr[] = {1, 2, 3, 4} Output: 1 The possible absolute differences are: {1, 2, 3, 1, 2, 1}Input: arr[] = {10, 2, 5, 4} Output: 1  
 
Approach:  
Traverse through the array and create a hash array to store the frequency of the array elements.Now, traverse through the hash array and calculate the distance between the two nearest elements.The frequency was calculated to check whether some element has frequency > 1 which means the absolute distance will be 0 i.e. |arr[i] – arr[i]|.
Traverse through the array and create a hash array to store the frequency of the array elements.
Now, traverse through the hash array and calculate the distance between the two nearest elements.
The frequency was calculated to check whether some element has frequency > 1 which means the absolute distance will be 0 i.e. |arr[i] – arr[i]|.
Below is the implementation of the above approach:  
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;#define MAX 100001 // Function to return the minimum// absolute difference between any// two elements of the arrayint getMinDiff(int arr[], int n){    // To store the frequency of each element    int freq[MAX] = { 0 };     for (int i = 0; i < n; i++) {         // Update the frequency of current element        freq[arr[i]]++;         // If current element appears more than once        // then the minimum absolute difference        // will be 0 i.e. |arr[i] - arr[i]|        if (freq[arr[i]] > 1)            return 0;    }     int mn = INT_MAX;     // Checking the distance between the nearest    // two elements in the frequency array    for (int i = 0; i < MAX; i++) {        if (freq[i] > 0) {            i++;            int cnt = 1;            while ((freq[i] == 0) && (i != MAX - 1)) {                cnt++;                i++;            }            mn = min(cnt, mn);            i--;        }    }     // Return the minimum absolute difference    return mn;} // Driver codeint main(){    int arr[] = { 1, 2, 3, 4 };    int n = sizeof(arr) / sizeof(int);     cout << getMinDiff(arr, n);     return 0;}
// Java implementation of the approachimport java.util.*; class GFG{ private static final int MAX = 100001; // Function to return the minimum// absolute difference between any// two elements of the arraystatic int getMinDiff(int arr[], int n){    // To store the frequency of each element    int[] freq = new int[MAX];    for(int i = 0; i < n; i++)    {        freq[i] = 0;    }    for (int i = 0; i < n; i++)    {         // Update the frequency of current element        freq[arr[i]]++;         // If current element appears more than once        // then the minimum absolute difference        // will be 0 i.e. |arr[i] - arr[i]|        if (freq[arr[i]] > 1)            return 0;    }     int mn = Integer.MAX_VALUE;     // Checking the distance between the nearest    // two elements in the frequency array    for (int i = 0; i < MAX; i++)    {        if (freq[i] > 0)        {            i++;            int cnt = 1;            while ((freq[i] == 0) && (i != MAX - 1))            {                cnt++;                i++;            }            mn = Math.min(cnt, mn);            i--;        }    }     // Return the minimum absolute difference    return mn;} // Driver codepublic static void main(String[] args){    int arr[] = { 1, 2, 3, 4 };    int n = arr.length;         System.out.println(getMinDiff(arr, n)); }} // This code is contributed by nidhi16bcs2007
# Python3 implementation of the approachMAX = 100001 # Function to return the minimum# absolute difference between any# two elements of the arraydef getMinDiff(arr, n):         # To store the frequency of each element    freq = [0 for i in range(MAX)]     for i in range(n):         # Update the frequency of current element        freq[arr[i]] += 1         # If current element appears more than once        # then the minimum absolute difference        # will be 0 i.e. |arr[i] - arr[i]|        if (freq[arr[i]] > 1):            return 0     mn = 10**9     # Checking the distance between the nearest    # two elements in the frequency array    for i in range(MAX):        if (freq[i] > 0):            i += 1            cnt = 1            while ((freq[i] == 0) and (i != MAX - 1)):                cnt += 1                i += 1            mn = min(cnt, mn)            i -= 1     # Return the minimum absolute difference    return mn # Driver codearr = [ 1, 2, 3, 4]n = len(arr) print(getMinDiff(arr, n)) # This code is contributed by Mohit Kumar
// C# implementation of the approachusing System; class GFG{     private static int MAX = 100001;         // Function to return the minimum    // absolute difference between any    // two elements of the array    static int getMinDiff(int []arr, int n)    {        // To store the frequency of each element        int[] freq = new int[MAX];        for(int i = 0; i < n; i++)        {            freq[i] = 0;        }        for (int i = 0; i < n; i++)        {                 // Update the frequency of current element            freq[arr[i]]++;                 // If current element appears more than once            // then the minimum absolute difference            // will be 0 i.e. |arr[i] - arr[i]|            if (freq[arr[i]] > 1)                return 0;        }             int mn = int.MaxValue;             // Checking the distance between the nearest        // two elements in the frequency array        for (int i = 0; i < MAX; i++)        {            if (freq[i] > 0)            {                i++;                int cnt = 1;                while ((freq[i] == 0) && (i != MAX - 1))                {                    cnt++;                    i++;                }                mn = Math.Min(cnt, mn);                i--;            }        }             // Return the minimum absolute difference        return mn;    }         // Driver code    public static void Main()    {        int []arr = { 1, 2, 3, 4 };        int n = arr.Length;                 Console.WriteLine(getMinDiff(arr, n));         }} // This code is contributed by AnkitRai01
<script> // JavaScript implementation of the approach  let MAX = 100001; // Function to return the minimum// absolute difference between any// two elements of the arrayfunction getMinDiff(arr,n){    // To store the frequency of each element    let freq=[];    for(let i = 0; i < n; i++)    {        freq[i] = 0;    }    for (let i = 0; i < n; i++)    {         // Update the frequency of current element        freq[arr[i]]++;         // If current element appears more than once        // then the minimum absolute difference        // will be 0 i.e. |arr[i] - arr[i]|        if (freq[arr[i]] > 1)            return 0;    }     let mn = Number.MAX_VALUE;     // Checking the distance between the nearest    // two elements in the frequency array    for (let i = 0; i < MAX; i++)    {        if (freq[i] > 0)        {            i++;            let cnt = 1;            while ((freq[i] == 0) && (i != MAX - 1))            {                cnt++;                i++;            }            mn = Math.min(cnt, mn);            i--;        }    }     // Return the minimum absolute difference    return mn;} // Driver code     let arr = [ 1, 2, 3, 4 ];    let n = arr.length;         document.write(getMinDiff(arr, n)); //contributed by 171fa07058     </script>
1
 
Time Complexity : O(MAX) 
Explanation : In  the above case we have taken MAX is equal to 100001, but we can take max as a maximum element in the array 
Space Complexity : O(MAX)
Explanation : We have taken frequency array of size MAX.
Alternate Shorter Implementation :  
Python3
# Python3 implementation of the approachimport itertools  arr = [1,2,3,4]diff_list = []  # Get the combinations of numbersfor n1, n2 in list(itertools.combinations(arr, 2)):     # Find the absolute difference    diff_list.append(abs(n1-n2))  print(min(diff_list))     # This code is contributed by mailprakashindia
1
 
Time  Complexity : O (r* ( n C r  ) ) 
Explanation : Here r is 2 because we are making combinations of two elements using iterator tool and n is length of given array, so if we calculate it , it will be
 O (n*(n-1) which will be O (n*n)
Space Complexity  : O ( ( n C r  ) )  ( Here, r=2)
Explanation : We have used list  to store all the combination of array and we have made diff_list array to store absolute difference
nidhiva
mohit kumar 29
ankthon
mailprakashindia
sravankumar8128
iramkhalid24
frequency-counting
Hash
Arrays
Competitive Programming
Arrays
Hash
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
Competitive Programming - A Complete Guide
Practice for cracking any coding interview
Arrow operator -> in C/C++ with Examples
Modulo 10^9+7 (1000000007)
Prefix Sum Array - Implementation and Applications in Competitive Programming