Minimum difference pair

Problem

Given an unsorted array, find the absolute minimum difference between any pair in given array.

Problem Constraints

1 <= |arr| <= 100000, 1 <= arr[i] <= 100000 

Example Input

Input 1:

A = [2, 4, 7, 9]

Input 2:

 A = [1, 3, 10, 5, 2, 17]

Example Output

Output 1:

2

Output 2:

1

Question Link

https://practice.geeksforgeeks.org/problems/minimum-difference-pair/0

Solution

We have to find the absolute minimum difference between any pair in given array.

Solution 1: Brute Force 

A brute force approach is to find the minimum absolute difference from each pair generated from the array. We simply use two loops to find the each pair and then find the minimum among them.

Algorithm: 

  • Initialize min = Integer.MAX_VALUE; 
  • Iterate (i) the array from left to right:
    • Iterate the array j=i+1 from left to right:
      • min = Math.min(min,Math.abs(A.get(j)-A.get(i))); 
  • Return min.

Here is the solution:

public class Solution {
public int findMinDifference(ArrayList<Integer> A){
int min = Integer.MAX_VALUE;
for(int i=0;i<A.size()-1;i++){
for(int j=i+1;j<A.size();j++){
min = Math.min(min,Math.abs(A.get(j)-A.get(i)));
}
}
return min;
}
}

Complexity Analysis:

  • Time Complexity: O(n^2)
  • Space Complexity: O(1)

Solution 2: Optimal Solution

In the brute force solution, we find each pair present in an array and then find the minimum. Let us try to understand with example:

A[] = [1, 3, 10, 5, 2, 17] 

Let us try to understand the solution. In the above example if we subtract 3 with 5. do we need to subtract 3 with 10 or 3 with 17. No, because 10 and 17 are greater than 5 and the difference between (10 and 3), (17 and 3) will always be greater than the difference between (3 and 5).

If we plot these numbers in a number line:

_____________1__2__3____5__________10_________________17___________________________

If we talk about 3, we only need to find the difference between 5 and 2 because these two adjacent element provides the minimum difference for element 3. we don't need to find the difference between any number greater than 5 and any number less than 2.

We say that for any element the minimum difference is given by the adjacent element of the right or left side of that element. 

What we do is first sort the complete array and then check the differences of the adjacent element.

Algorithm:

  • Sort the Array.
  • Initialize min = Integer.MAX_VALUE.
  • Iterate the array from left to right
    • min = Math.min(min,A[i]-A[i-1]) 

Here is the solution:

class Solution {
public int findMinDifference(int[] A){
Arrays.sort(a);
int min = Integer.MAX_VALUE;
for(int i=1;i<n;i++){
    int val = a[i]-a[i-1];
    min = Math.min(val,min);
}
return min;
}
}

Complexity Analysis:

  • Time Complexity: O(nlogn)
  • Space Complexity: O(1)

Comments

Popular posts from this blog

Beggars Outside Temple

Difference between Static Array and Dynamic Array

Rain Water Trapped