Find minimum difference between any two elements | Set 2
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]|.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
#define MAX 100001
int getMinDiff( int arr[], int n)
{
int freq[MAX] = { 0 };
for ( int i = 0; i < n; i++) {
freq[arr[i]]++;
if (freq[arr[i]] > 1)
return 0;
}
int mn = INT_MAX;
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 mn;
}
int main()
{
int arr[] = { 1, 2, 3, 4 };
int n = sizeof (arr) / sizeof ( int );
cout << getMinDiff(arr, n);
return 0;
}
|
Java
import java.util.*;
class GFG
{
private static final int MAX = 100001 ;
static int getMinDiff( int arr[], int n)
{
int [] freq = new int [MAX];
for ( int i = 0 ; i < n; i++)
{
freq[i] = 0 ;
}
for ( int i = 0 ; i < n; i++)
{
freq[arr[i]]++;
if (freq[arr[i]] > 1 )
return 0 ;
}
int mn = Integer.MAX_VALUE;
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 mn;
}
public static void main(String[] args)
{
int arr[] = { 1 , 2 , 3 , 4 };
int n = arr.length;
System.out.println(getMinDiff(arr, n));
}
}
|
Python3
MAX = 100001
def getMinDiff(arr, n):
freq = [ 0 for i in range ( MAX )]
for i in range (n):
freq[arr[i]] + = 1
if (freq[arr[i]] > 1 ):
return 0
mn = 10 * * 9
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 mn
arr = [ 1 , 2 , 3 , 4 ]
n = len (arr)
print (getMinDiff(arr, n))
|
C#
using System;
class GFG
{
private static int MAX = 100001;
static int getMinDiff( int []arr, int n)
{
int [] freq = new int [MAX];
for ( int i = 0; i < n; i++)
{
freq[i] = 0;
}
for ( int i = 0; i < n; i++)
{
freq[arr[i]]++;
if (freq[arr[i]] > 1)
return 0;
}
int mn = int .MaxValue;
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 mn;
}
public static void Main()
{
int []arr = { 1, 2, 3, 4 };
int n = arr.Length;
Console.WriteLine(getMinDiff(arr, n));
}
}
|
Javascript
<script>
let MAX = 100001;
function getMinDiff(arr,n)
{
let freq=[];
for (let i = 0; i < n; i++)
{
freq[i] = 0;
}
for (let i = 0; i < n; i++)
{
freq[arr[i]]++;
if (freq[arr[i]] > 1)
return 0;
}
let mn = Number.MAX_VALUE;
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 mn;
}
let arr = [ 1, 2, 3, 4 ];
let n = arr.length;
document.write(getMinDiff(arr, n));
</script>
|
Time Complexity : O(n)
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
Auxiliary Space: O(MAX)
Explanation: We have taken a frequency array of size MAX.
Alternate Shorter Implementation :
C++
#include<iostream>
#include<cmath>
#include<vector>
#include<algorithm>
using namespace std;
int main() {
vector< int > arr = {1, 2, 3, 4};
vector< int > diff_list;
for ( int i = 0; i < arr.size(); i++) {
for ( int j = i+1; j < arr.size(); j++) {
diff_list.push_back( abs (arr[i] - arr[j]));
}
}
int min_diff = *min_element(diff_list.begin(), diff_list.end());
cout << min_diff << endl;
return 0;
}
|
Python3
import itertools
arr = [ 1 , 2 , 3 , 4 ]
diff_list = []
for n1, n2 in list (itertools.combinations(arr, 2 )):
diff_list.append( abs (n1 - n2))
print ( min (diff_list))
|
Javascript
let arr = [1, 2, 3, 4];
let diffList = [];
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
diffList.push(Math.abs(arr[i] - arr[j]));
}
}
let minDiff = Math.min(...diffList);
console.log(minDiff);
|
Java
import java.util.ArrayList;
import java.util.Collections;
public class Main {
public static void main(String[] args)
{
ArrayList<Integer> arr = new ArrayList<Integer>();
arr.add( 1 );
arr.add( 2 );
arr.add( 3 );
arr.add( 4 );
ArrayList<Integer> diff_list = new ArrayList<
Integer>();
for ( int i = 0 ; i < arr.size(); i++) {
for ( int j = i + 1 ; j < arr.size(); j++) {
diff_list.add(
Math.abs(arr.get(i) - arr.get(j)));
}
}
int min_diff = Collections.min(diff_list);
System.out.println(min_diff);
}
}
|
C#
using System;
using System.Collections.Generic;
using System.Linq;
class Program {
static void Main( string [] args)
{
List< int > arr = new List< int >{ 1, 2, 3, 4 };
List< int > diff_list = new List< int >();
for ( int i = 0; i < arr.Count; i++) {
for ( int j = i + 1; j < arr.Count; j++) {
diff_list.Add(Math.Abs(arr[i] - arr[j]));
}
}
int min_diff = diff_list.Min();
Console.WriteLine(min_diff);
}
}
|
Time Complexity: O (r* ( n C r ) )
Explanation: Here r is 2 because we are making combinations of two elements using the iterator tool and n is the length of the given array, so if we calculate it, it will be O (n*(n-1) which will be O (n*n)
Auxiliary Space: O ( ( n C r ) ) ( Here, r=2)
Explanation: We have used the list to store all the combinations of arrays and we have made diff_list array to store absolute difference
Last Updated :
31 Mar, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...