Find minimum difference between any two elements | Set 2
Last Updated :
31 Mar, 2023
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++
// 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 array
int 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 code
int main()
{
int arr[] = { 1, 2, 3, 4 };
int n = sizeof(arr) / sizeof(int);
cout << getMinDiff(arr, n);
return 0;
}
Java
// Java implementation of the approach
import java.util.*;
class GFG
{
private static final 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 = 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 code
public 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
# Python3 implementation of the approach
MAX = 100001
# Function to return the minimum
# absolute difference between any
# two elements of the array
def 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 code
arr = [ 1, 2, 3, 4]
n = len(arr)
print(getMinDiff(arr, n))
# This code is contributed by Mohit Kumar
C#
// C# implementation of the approach
using 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
JavaScript
<script>
// JavaScript implementation of the approach
let MAX = 100001;
// Function to return the minimum
// absolute difference between any
// two elements of the array
function 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>
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;
// Get the combinations of numbers
for(int i = 0; i < arr.size(); i++) {
for(int j = i+1; j < arr.size(); j++) {
// Find the absolute difference
diff_list.push_back(abs(arr[i] - arr[j]));
}
}
// Find the minimum difference
int min_diff = *min_element(diff_list.begin(), diff_list.end());
cout << min_diff << endl;
return 0;
}
Python3
# Python3 implementation of the approach
import itertools
arr = [1,2,3,4]
diff_list = []
# Get the combinations of numbers
for 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
JavaScript
let arr = [1, 2, 3, 4];
let diffList = [];
// Get the combinations of numbers
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
// Find the absolute difference
diffList.push(Math.abs(arr[i] - arr[j]));
}
}
// Find the minimum difference
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>(); // Get the combinations of numbers
for (int i = 0; i < arr.size(); i++) {
for (int j = i + 1; j < arr.size(); j++) {
// Find the absolute difference
diff_list.add(
Math.abs(arr.get(i) - arr.get(j)));
}
}
// Find the minimum difference
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>();
// Get the combinations of numbers
for (int i = 0; i < arr.Count; i++) {
for (int j = i + 1; j < arr.Count; j++) {
// Find the absolute difference
diff_list.Add(Math.Abs(arr[i] - arr[j]));
}
}
// Find the minimum difference
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
Similar Reads
Find minimum difference between any two elements (pair) in given array Given an unsorted array, find the minimum difference between any pair in the given array. Examples : Input: {1, 5, 3, 19, 18, 25}Output: 1Explanation: Minimum difference is between 18 and 19 Input: {30, 5, 20, 9}Output: 4Explanation: Minimum difference is between 5 and 9 Input: {1, 19, -4, 31, 38, 2
15+ min read
Find Maximized difference between two elements for every index of given Arrays Given two arrays A[] and B[] of the same length N. the task is to find a pair (X, Y) for two numbers Ai (number at i index of array A) and Bi(number at i index of array B) such that the value of |X-Y| is maximized for each index and the pair satisfies the following conditions: 1 ⤠X, Y ⤠Bigcd(X, Y)
6 min read
Array element with minimum sum of absolute differences | Set 2 Given an array arr[] consisting of N positive integers, the task is to find an array element X such that sum of its absolute differences with every array element is minimum. Examples: Input: arr[] = {1, 2, 3, 4, 5}Output: 3Explanation: For element arr[0](= 1): |(1 - 1)| + |(2 - 1)| + |(3 - 1)| + |(4
7 min read
k-th smallest absolute difference of two elements in an array We are given an array of size n containing positive integers. The absolute difference between values at indices i and j is |a[i] - a[j]|. There are n*(n-1)/2 such pairs and we are asked to print the kth (1 <= k <= n*(n-1)/2) as the smallest absolute difference among all these pairs. Examples:
9 min read
Find Maximum Difference Between any Two Pairs By Following Operations Optimally Given an array X[] of length N along with A and B. You can apply below type of operations: Operation 1: Choose two different indices, delete elements at both indices and insert the sum of them in X[]. This operation decrements A by 1.Operation 2: Choose two different indices, delete elements at both
10 min read