Open In App

Find all pairs in an Array in sorted order with minimum absolute difference

Last Updated : 08 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given an integer array arr[] of size N, the task is to find all distinct pairs having minimum absolute difference and print them in ascending order. 

Examples:

Input: arr[] = {4, 2, 1, 3}
Output: {1, 2}, {2, 3}, {3, 4}
Explanation: The minimum absolute difference between pairs is 1.

Input: arr[] = {1, 3, 8, 10, 15}
Output: {1, 3}, {8, 10}
Explanation: The minimum absolute difference between the pairs {1, 3}, {8, 10} is 2. 

 

Approach (Using Nested Loop):

The basic idea is to compare each pair of elements in the array and find the pair(s) with the minimum absolute difference.

  1. Sort the array arr in non-decreasing order.
  2. Initialize a variable min_diff to store the minimum absolute difference between pairs. Set min_diff to a very large value (e.g., INT_MAX).
  3. Initialize a vector pairs to store all pairs having the minimum absolute difference.
  4. Iterate through the array arr using a nested loop. For each pair of elements (arr[i], arr[j]) such that i < j, compute the absolute difference diff = abs(arr[i] – arr[j]). If diff < min_diff, update min_diff with diff and clear the vector pairs. Add the pair (arr[i], arr[j]) to the vector pairs.
  5. If diff == min_diff, add the pair (arr[i], arr[j]) to the vector pairs.
  6. Return the vector pairs containing all pairs having the minimum absolute difference.

Below is the implementation of the above approach:

C++




#include <bits/stdc++.h>
using namespace std;
 
// Function to return all
// pairs having minimal absolute difference
vector<vector<int>> minAbsDiffPairs(vector<int>& arr) {
    // Sort the array in non-decreasing order
    sort(arr.begin(), arr.end());
 
    // Find the minimum absolute difference between pairs
    int min_diff = INT_MAX;
    vector<vector<int>> pairs;
    for (int i = 0; i < arr.size(); i++) {
        for (int j = i+1; j < arr.size(); j++) {
            int diff = abs(arr[i] - arr[j]);
            if (diff < min_diff) {
                min_diff = diff;
                pairs.clear();
                pairs.push_back({arr[i], arr[j]});
            }
            else if (diff == min_diff) {
                pairs.push_back({arr[i], arr[j]});
            }
        }
    }
 
    return pairs;
}
 
// Driver Code
int main() {
    vector<int> arr = { 4, 2, 1, 3 };
    vector<vector<int>> pairs = minAbsDiffPairs(arr);
 
    // Print all pairs
    for (auto v : pairs) {
        cout << v[0] << " " << v[1] << endl;
    }
 
    return 0;
}


Java




import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
 
public class Main {
    // Function to return all pairs having minimal absolute difference
    public static List<List<Integer>> minAbsDiffPairs(int[] arr) {
        // Sort the array in non-decreasing order
        Arrays.sort(arr);
 
        // Find the minimum absolute difference between pairs
        int minDiff = Integer.MAX_VALUE;
        List<List<Integer>> pairs = new ArrayList<>();
 
        for (int i = 0; i < arr.length - 1; i++) {
            int diff = Math.abs(arr[i] - arr[i + 1]);
 
            // If the current difference is smaller than the minimum difference so far
            if (diff < minDiff) {
                minDiff = diff;
                pairs.clear();
                pairs.add(Arrays.asList(arr[i], arr[i + 1]));
            }
            // If the current difference is equal to the minimum difference so far
            else if (diff == minDiff) {
                pairs.add(Arrays.asList(arr[i], arr[i + 1]));
            }
        }
 
        return pairs;
    }
 
    public static void main(String[] args) {
        int[] arr = { 4, 2, 1, 3 };
        List<List<Integer>> pairs = minAbsDiffPairs(arr);
 
        // Print all pairs
        for (List<Integer> pair : pairs) {
            System.out.println(pair.get(0) + " " + pair.get(1));
        }
    }
}


Python




def min_abs_diff_pairs(arr):
    # Sort the array in non-decreasing order
    arr.sort()
 
    # Find the minimum absolute difference between pairs
    min_diff = float('inf')
    pairs = []
    for i in range(len(arr)):
        for j in range(i + 1, len(arr)):
            diff = abs(arr[i] - arr[j])
            if diff < min_diff:
                min_diff = diff
                pairs = [[arr[i], arr[j]]]
            elif diff == min_diff:
                pairs.append([arr[i], arr[j]])
 
    return pairs
 
# Driver Code
if __name__ == "__main__":
    arr = [4, 2, 1, 3]
    pairs = min_abs_diff_pairs(arr)
 
    # Print all pairs
    for v in pairs:
        print(v[0], v[1])
        


C#




using System;
using System.Collections.Generic;
using System.Linq;
 
public class GFG {
    // Function to return all pairs having minimal absolute
    // difference
    public static List<List<int> >
    MinAbsDiffPairs(List<int> arr)
    {
        // Sort the array in non-decreasing order
        arr.Sort();
 
        // Find the minimum absolute difference between
        // pairs
        int min_diff = int.MaxValue;
        List<List<int> > pairs = new List<List<int> >();
        for (int i = 0; i < arr.Count; i++) {
            for (int j = i + 1; j < arr.Count; j++) {
                int diff = Math.Abs(arr[i] - arr[j]);
                if (diff < min_diff) {
                    min_diff = diff;
                    pairs.Clear();
                    pairs.Add(
                        new List<int>{ arr[i], arr[j] });
                }
                else if (diff == min_diff) {
                    pairs.Add(
                        new List<int>{ arr[i], arr[j] });
                }
            }
        }
 
        return pairs;
    }
 
    public static void Main()
    {
        List<int> arr = new List<int>{ 4, 2, 1, 3 };
        List<List<int> > pairs = MinAbsDiffPairs(arr);
 
        // Print all pairs
        foreach(var v in pairs)
        {
            Console.WriteLine(v[0] + " " + v[1]);
        }
    }
}


Javascript




// Function to return all
// pairs having minimal absolute difference
function minAbsDiffPairs(arr) {
    // Sort the array in non-decreasing order
    arr.sort((a, b) => a - b);
 
    // Find the minimum absolute difference between pairs
    let min_diff = Number.MAX_VALUE;
    let pairs=[];
    for (let i = 0; i < arr.length; i++) {
        for (let j = i+1; j < arr.length; j++) {
            let diff = Math.abs(arr[i] - arr[j]);
            if (diff < min_diff) {
                min_diff = diff;
                pairs=[[arr[i], arr[j]]];
            }
            else if (diff == min_diff) {
                pairs.push([arr[i], arr[j]]);
            }
        }
    }
 
    return pairs;
}
 
// Driver Code
let arr = [ 4, 2, 1, 3 ];
let pairs = minAbsDiffPairs(arr);
 
// Print all pairs
for (let v of pairs) {
    console.log(v[0]+  " "+  v[1]);
}


Output:

     1 2
2 3
3 4

Time Complexity: O(n^2 log n), where n is the size of the input array. This is because we are using a nested loop to compare each pair of elements in the array, and the sorting operation inside the outer loop has a time complexity of O(n log n). 

Auxiliary Space: O(k), where k is the number of pairs having the minimum absolute difference.

Approach: The idea is to consider the absolute difference of the adjacent elements of the sorted array. Follow the steps below to solve the problem:

  • Sort the given array arr[].
  • Compare all adjacent pairs in the sorted array and find the minimum absolute difference between all adjacent pairs.
  • Finally, print all the adjacent pairs having differences equal to the minimum absolute difference.

Below is the implementation of the above code:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to return all
// pairs having minimal absolute difference
vector<vector<int> > minAbsDiffPairs(vector<int>& arr)
{
 
    vector<vector<int> > ans;
    int n = arr.size();
 
    // Sort the array
    sort(arr.begin(), arr.end());
 
    // Stores the minimal absolute difference
    int minDiff = INT_MAX;
 
    for (int i = 0; i < n - 1; i++)
        minDiff = min(minDiff, abs(arr[i] - arr[i + 1]));
 
    for (int i = 0; i < n - 1; i++) {
        vector<int> pair;
        if (abs(arr[i] - arr[i + 1]) == minDiff) {
            pair.push_back(min(arr[i], arr[i + 1]));
            pair.push_back(max(arr[i], arr[i + 1]));
            ans.push_back(pair);
        }
    }
 
    return ans;
}
 
// Driver Code
int main()
{
    vector<int> arr = { 4, 2, 1, 3 };
    int N = (sizeof arr) / (sizeof arr[0]);
 
    vector<vector<int> > pairs = minAbsDiffPairs(arr);
 
    // Print all pairs
    for (auto v : pairs)
        cout << v[0] << " " << v[1] << endl;
    return 0;
}


Java




// Java program for the above approach
import java.util.ArrayList;
import java.util.Collections;
 
class GFG
{
   
    // Function to return all
    // pairs having minimal absolute difference
    static ArrayList<ArrayList<Integer>> minAbsDiffPairs(ArrayList<Integer> arr) {
 
        ArrayList<ArrayList<Integer>> ans = new ArrayList<ArrayList<Integer>>();
        int n = arr.size();
 
        // Sort the array
        Collections.sort(arr);
 
        // Stores the minimal absolute difference
        int minDiff = Integer.MAX_VALUE;
 
        for (int i = 0; i < n - 1; i++)
            minDiff = Math.min(minDiff, Math.abs(arr.get(i) - arr.get(i + 1)));
 
        for (int i = 0; i < n - 1; i++) {
            ArrayList<Integer> pair = new ArrayList<Integer>();
            if (Math.abs(arr.get(i) - arr.get(i + 1)) == minDiff) {
                pair.add(Math.min(arr.get(i), arr.get(i + 1)));
                pair.add(Math.max(arr.get(i), arr.get(i + 1)));
                ans.add(pair);
            }
        }
 
        return ans;
    }
 
    // Driver Code
    public static void main(String args[]) {
        ArrayList<Integer> arr = new ArrayList<Integer>();
        arr.add(4);
        arr.add(2);
        arr.add(1);
        arr.add(3);
 
        ArrayList<ArrayList<Integer>> pairs = minAbsDiffPairs(arr);
 
        // Print all pairs
        // System.out.println(pairs);
        for (ArrayList<Integer> v : pairs) {
            for (int w : v)
                System.out.print(w + " ");
            System.out.println("");
        }
    }
}
 
// This code is contributed by saurabh_jaiswal.


Python3




# Python3 program for the above approach
import math as Math
 
# Function to return all pairs having
# minimal absolute difference
def minAbsDiffPairs(arr):
 
    ans = []
    n = len(arr)
 
    # Sort the array
    arr.sort()
 
    # Stores the minimal absolute difference
    minDiff = 10 ** 9
 
    for i in range(n - 1):
        minDiff = min(minDiff, Math.fabs(arr[i] -
                                         arr[i + 1]))
 
    for i in range(n - 1):
        pair = []
        if (Math.fabs(arr[i] - arr[i + 1]) == minDiff):
            pair.append(min(arr[i], arr[i + 1]))
            pair.append(max(arr[i], arr[i + 1]))
            ans.append(pair)
             
    return ans
 
# Driver Code
arr = [ 4, 2, 1, 3 ]
N = len(arr)
 
pairs = minAbsDiffPairs(arr)
 
# Print all pairs
for v in pairs:
    print(f"{v[0]} {v[1]}")
 
# This code is contributed by gfgking


C#




// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG
{
 
  // Function to return all
  // pairs having minimal Absolute difference
  static List<List<int>> minAbsDiffPairs(List<int> arr) {
 
    List<List<int>> ans = new List<List<int>>();
    int n = arr.Count;
 
    // Sort the array
    arr.Sort();
 
    // Stores the minimal Absolute difference
    int minDiff = int.MaxValue;
 
    for (int i = 0; i < n - 1; i++)
      minDiff = Math.Min(minDiff, Math.Abs(arr[i] - arr[i + 1]));
 
    for (int i = 0; i < n - 1; i++) {
      List<int> pair = new List<int>();
      if (Math.Abs(arr[i] - arr[i + 1]) == minDiff) {
        pair.Add(Math.Min(arr[i], arr[i + 1]));
        pair.Add(Math.Max(arr[i], arr[i + 1]));
        ans.Add(pair);
      }
    }
 
    return ans;
  }
 
  // Driver Code
  public static void Main()
  {
    List<int> arr = new List<int>();
    arr.Add(4);
    arr.Add(2);
    arr.Add(1);
    arr.Add(3);
 
    List<List<int>> pairs = minAbsDiffPairs(arr);
 
    // Print all pairs
    // System.out.println(pairs);
    foreach (List<int> v in pairs)
    {
      foreach (int w in v)
        Console.Write(w + " ");
      Console.WriteLine("");
    }
  }
}
 
// This code is contributed by saurabh_jaiswal.


Javascript




<script>
    // JavaScript code for the above approach
 
    // Function to return all
    // pairs having minimal absolute difference
    function minAbsDiffPairs(arr)
    {
 
      let ans = [];
      let n = arr.length;
 
      // Sort the array
      arr.sort(function (a, b) { return a - b })
 
      // Stores the minimal absolute difference
      let minDiff = Number.MAX_VALUE;
 
      for (let i = 0; i < n - 1; i++)
        minDiff = Math.min(minDiff, Math.abs(arr[i] - arr[i + 1]));
 
      for (let i = 0; i < n - 1; i++) {
        let pair = [];
        if (Math.abs(arr[i] - arr[i + 1]) == minDiff) {
          pair.push(Math.min(arr[i], arr[i + 1]));
          pair.push(Math.max(arr[i], arr[i + 1]));
          ans.push(pair);
        }
      }
      return ans;
    }
 
    // Driver Code
    let arr = [4, 2, 1, 3];
    let N = arr.length;
 
    let pairs = minAbsDiffPairs(arr);
 
    // Print all pairs
    for (let v of pairs)
      document.write(v[0] + " " + v[1] + '<br>')
 
  // This code is contributed by Potta Lokesh
  </script>


Output

1 2
2 3
3 4







Time Complexity: O(NlogN)
Auxiliary Space: O(N), since N extra space has been taken.

 



Similar Reads

Minimize sum of absolute difference between all pairs of array elements by decrementing and incrementing pairs by 1
Given an array arr[] ( 1-based indexing ) consisting of N integers, the task is to find the minimum sum of the absolute difference between all pairs of array elements by decrementing and incrementing any pair of elements by 1 any number of times. Examples: Input: arr[] = {1, 2, 3}Output: 0Explanation:Modify the array elements by performing the foll
5 min read
Minimum value of maximum absolute difference of all adjacent pairs in an Array
Given an array arr, containing non-negative integers and (-1)s, of size N, the task is to replace those (-1)s with a common non-negative integer such that the maximum absolute difference of all adjacent pairs is minimum. Print this minimum possible value of the maximum absolute difference. Examples: Input: arr = {-1, -1, 11, -1, 3, -1} Output: 4 Re
9 min read
Count of all pairs in an Array with minimum absolute difference
Given an integer array arr[] of size N, the task is to count the total number of distinct pairs having minimum absolute difference. Examples: Input: arr[] = {4, 2, 1, 3} Output: 3 Explanation: The minimum absolute difference between the pairs {1, 2}, {2, 3}, {3, 4} is 1.Input: arr[] = {1, 3, 8, 10, 15} Output: 2 Explanation: The minimum absolute di
5 min read
Print all repeating adjacent pairs in sorted order from an array
Given an array arr[] consisting of N integers, the task is to print all adjacent integer pairs from the array which appears more than once in the given array. If the array contains more than one such pair, print all pairs in sorted order. Examples: Input: arr[] = {1, 2, 5, 1, 2}Output:1 2Explanation:1 2 is the only repeating integer pair in the arr
7 min read
Print all elements in sorted order from row and column wise sorted matrix
Given an n x n matrix, where every row and column is sorted in non-decreasing order. Print all elements of the matrix in sorted order. Example: Input: mat[][] = { {10, 20, 30, 40}, {15, 25, 35, 45}, {27, 29, 37, 48}, {32, 33, 39, 50}, };Output: 10 15 20 25 27 29 30 32 33 35 37 39 40 45 48 50 Recommended PracticeSorted matrixTry It! We can use Young
26 min read
heapq in Python to print all elements in sorted order from row and column wise sorted matrix
Given an n x n matrix, where every row and column is sorted in non-decreasing order. Print all elements of matrix in sorted order. Examples: Input : mat= [[10, 20, 30, 40], [15, 25, 35, 45], [27, 29, 37, 48], [32, 33, 39, 50]] Output : Elements of matrix in sorted order [10, 15, 20, 25, 27, 29, 30, 32, 33, 35, 37, 39, 40, 45, 48, 50] This problem h
2 min read
Calculate absolute difference between minimum and maximum sum of pairs in an array
Given an array arr[] consisting of N integers, the task is to find the absolute difference between the minimum and maximum sum of any pairs of elements (arr[i], arr[j]) such that (i &lt; j) and (arr[i] &lt; arr[j]). Examples: Input: arr[] = {1, 2, 4, 7}Output: 8Explanation: All possible pairs are: (1, 2) ? Sum = 3(1, 4) ? Sum = 5(1, 7) ? Sum = 8(2,
9 min read
Count pairs from an array with absolute difference not less than the minimum element in the pair
Given an array arr[] consisting of N positive integers, the task is to find the number of pairs (arr[i], arr[j]) such that absolute difference between the two elements is at least equal to the minimum element in the pair. Examples: Input: arr[] = {1, 2, 2, 3}Output: 3Explanation:Following are the pairs satisfying the given criteria: (arr[0], arr[1]
14 min read
Make all array elements equal by repeated subtraction of absolute difference of pairs from their maximum
Given an array arr[] consisting of N integers, the task is to make all array elements equal by selecting any pair of integers from the array and replacing the larger integer from the pair with their absolute difference any number of times. Print the final value of all array elements. Examples: Input: arr[] ={2, 3, 4}Output: 1Explanation: Step 1: Pe
5 min read
Count Non-Repeating array elements after inserting absolute difference between all possible pairs
Given an array arr[] of size N, the task is to maximize the count of distinct array elements by repeatedly inserting the absolute difference between all possible pairs of the given array. Examples: Input: arr[] = { 2, 4, 16 }Output: 9 Explanation: Inserting (arr[2] - arr[1]) modifies arr[] to { 2, 4, 12, 16 } Inserting (arr[2] - arr[1]) modifies ar
7 min read