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.
1def minimumAbsDifference(arr):
2 arr.sort()
3 min_diff = float('inf')
4 result = []
5 for i in range(1, len(arr)):
6 diff = arr[i] - arr[i - 1]
7 if diff < min_diff:
8 min_diff = diff
9 result = [[arr[i - 1], arr[i]]]
10 elif diff == min_diff:
11 result.append([arr[i - 1], arr[i]])
12 return result
13
This Python solution sorts the list initially and calculates the difference between consecutive elements. It keeps track of the minimum difference and collects pairs that have this difference, placing them in the result list accordingly.
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.
1#include <vector>
2#include <algorithm>
3
4std::vector<std::vector<int>> minimumAbsDifference(std::vector<int>& arr) {
5 int minDiff = INT_MAX;
6 std::vector<std::vector<int>> result;
7 for (size_t i = 0; i < arr.size(); ++i) {
8 for (size_t j = i + 1; j < arr.size(); ++j) {
9 int diff = std::abs(arr[i] - arr[j]);
10 if (diff < minDiff) {
11 minDiff = diff;
12 result.clear();
13 result.push_back({arr[i], arr[j]});
14 } else if (diff == minDiff) {
15 result.push_back({arr[i], arr[j]});
16 }
17 }
18 }
19 return result;
20}
21
This C++ solution systematically checks every element pair, calculating their disparity and updating the recorded minimal difference before accumulating the appropriate pairs in the result array that is ultimately returned.