The first approach involves sorting the array and then iterating through it to find the pairs with the minimum absolute difference. By sorting, the smallest differences can only occur between consecutive elements. Hence, we sort the array and compute differences between adjacent elements to find the minimum difference.
Steps:
Time Complexity: O(n log n), due to sorting the array. Space Complexity: O(1), not considering the output space.
1var minimumAbsDifference = function(arr) {
2 arr.sort((a, b) => a - b);
3 let minDiff = Infinity;
4 let result = [];
5 for (let i = 1; i < arr.length; i++) {
6 let diff = arr[i] - arr[i - 1];
7 if (diff < minDiff) {
8 minDiff = diff;
9 result = [[arr[i - 1], arr[i]]];
10 } else if (diff === minDiff) {
11 result.push([arr[i - 1], arr[i]]);
12 }
13 }
14 return result;
15};
16
This JavaScript approach involves sorting the array and checking consecutive differences. It stores pairs with the minimum found difference into the result array.
The second approach compares all pairs of elements to determine their absolute differences. This method ensures that all possible pairs are considered, and the pairs with the minimum difference are identified. Although not as efficient as the first approach, it explicitly checks every possible pair.
Steps:
Time Complexity: O(n^2), considering all pair combinations. Space Complexity: O(1), excluding result space.
1using System;
2using System.Collections.Generic;
3
4public class Solution {
5 public IList<IList<int>> MinimumAbsDifference(int[] arr) {
6 int minDiff = int.MaxValue;
7 List<IList<int>> result = new List<IList<int>>();
8 for (int i = 0; i < arr.Length; i++) {
9 for (int j = i + 1; j < arr.Length; j++) {
10 int diff = Math.Abs(arr[i] - arr[j]);
11 if (diff < minDiff) {
12 minDiff = diff;
13 result.Clear();
14 result.Add(new List<int> { arr[i], arr[j] });
15 } else if (diff == minDiff) {
16 result.Add(new List<int> { arr[i], arr[j] });
17 }
18 }
19 }
20 return result;
21 }
22}
23
The C# solution thoroughly examines each set of potential pairs, calculates their differences, updates the minimum difference determined, and stores the results in a list formatted for return.