Facebook Pixel

1200. Minimum Absolute Difference

Problem Description

You are given an array of distinct integers arr. Your task is to find all pairs of elements that have the minimum absolute difference among all possible pairs in the array.

The problem asks you to:

  1. Find the minimum absolute difference between any two elements in the array
  2. Return all pairs [a, b] that have this minimum difference

Each pair in your result must satisfy these conditions:

  • Both a and b come from the original array arr
  • a < b (the smaller element comes first in the pair)
  • The difference b - a equals the minimum absolute difference found in step 1

The pairs should be returned in ascending order.

For example, if arr = [4, 2, 1, 3], after sorting we get [1, 2, 3, 4]. The differences between adjacent elements are: 2-1=1, 3-2=1, 4-3=1. The minimum difference is 1. So we return all pairs with difference 1: [[1,2], [2,3], [3,4]].

The solution approach sorts the array first because the minimum absolute difference will always occur between adjacent elements in a sorted array. After sorting, it finds the minimum difference by checking all adjacent pairs, then collects all pairs that have this minimum difference.

Quick Interview Experience
Help others by sharing your interview experience
Have you seen this problem before?

Intuition

The key insight is that in an unsorted array, we'd need to check every possible pair to find the minimum difference, which would take O(nΒ²) time. However, we can make an important observation: the minimum absolute difference between any two elements will always occur between elements that are close to each other in value.

Think about it this way - if we have numbers like [10, 3, 15, 7], the smallest difference won't be between 3 and 15 (difference of 12), but rather between numbers that are numerically closer, like 7 and 10 (difference of 3).

This naturally leads us to sorting the array first. Once sorted, elements with similar values become adjacent to each other. For instance, [3, 7, 10, 15]. Now we can guarantee that the minimum absolute difference must exist between some pair of adjacent elements. Why? Because for any element, its closest neighbors in value are the elements immediately before and after it in the sorted array.

After sorting, we make two passes through the array:

  1. First pass: Check all adjacent pairs to find the minimum difference value
  2. Second pass: Collect all adjacent pairs that have this minimum difference

The beauty of this approach is that we reduce the problem from checking all n*(n-1)/2 pairs to just checking n-1 adjacent pairs. Since the array contains distinct integers, we don't need to worry about duplicate values, and the pairs naturally come out in ascending order because we're traversing a sorted array from left to right.

Learn more about Sorting patterns.

Solution Approach

The solution follows a straightforward approach using sorting and two passes through the array:

Step 1: Sort the array

arr.sort()

We sort the array in ascending order. This ensures that elements close in value become adjacent, allowing us to find the minimum difference by only checking consecutive pairs.

Step 2: Find the minimum absolute difference

mi = min(b - a for a, b in pairwise(arr))

We use the pairwise function to iterate through all adjacent pairs (a, b) in the sorted array. For each pair, we calculate the difference b - a (which is always positive since the array is sorted). The min() function finds the smallest difference among all adjacent pairs.

The pairwise(arr) function generates consecutive pairs from the array. For example, if arr = [1, 3, 6, 10], then pairwise(arr) yields (1, 3), (3, 6), (6, 10).

Step 3: Collect all pairs with minimum difference

return [[a, b] for a, b in pairwise(arr) if b - a == mi]

We make another pass through the adjacent pairs using list comprehension. For each pair (a, b), we check if the difference b - a equals the minimum difference mi we found. If it does, we include the pair [a, b] in our result list.

Time Complexity: O(n log n) where n is the length of the array. The sorting step dominates the time complexity.

Space Complexity: O(1) if we don't count the output array. The sorting can be done in-place, and we only use a constant amount of extra space for the variable mi.

Ready to land your dream job?

Unlock your dream job with a 5-minute evaluator for a personalized learning plan!

Start Evaluator

Example Walkthrough

Let's walk through the solution with arr = [40, 11, 26, 27, -20].

Step 1: Sort the array After sorting: arr = [-20, 11, 26, 27, 40]

Step 2: Find the minimum absolute difference We examine all adjacent pairs:

  • Pair (-20, 11): difference = 11 - (-20) = 31
  • Pair (11, 26): difference = 26 - 11 = 15
  • Pair (26, 27): difference = 27 - 26 = 1
  • Pair (27, 40): difference = 40 - 27 = 13

The minimum difference is 1.

Step 3: Collect all pairs with minimum difference We go through the adjacent pairs again and collect those with difference equal to 1:

  • Pair (-20, 11): difference = 31 β‰  1 (skip)
  • Pair (11, 26): difference = 15 β‰  1 (skip)
  • Pair (26, 27): difference = 1 = 1 βœ“ (include)
  • Pair (27, 40): difference = 13 β‰  1 (skip)

Result: [[26, 27]]

The final answer contains only one pair because [26, 27] is the only adjacent pair in the sorted array with the minimum difference of 1.

Solution Implementation

1class Solution:
2    def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]:
3        # Sort the array to find adjacent pairs with minimum difference
4        arr.sort()
5      
6        # Find the minimum absolute difference between consecutive elements
7        min_diff = float('inf')
8        for i in range(1, len(arr)):
9            diff = arr[i] - arr[i - 1]
10            min_diff = min(min_diff, diff)
11      
12        # Collect all pairs that have the minimum absolute difference
13        result = []
14        for i in range(1, len(arr)):
15            if arr[i] - arr[i - 1] == min_diff:
16                result.append([arr[i - 1], arr[i]])
17      
18        return result
19
1class Solution {
2    public List<List<Integer>> minimumAbsDifference(int[] arr) {
3        // Sort the array to ensure adjacent elements have the smallest differences
4        Arrays.sort(arr);
5      
6        int arrayLength = arr.length;
7      
8        // Initialize minimum difference with a large value (2^30)
9        int minDifference = 1 << 30;
10      
11        // Find the minimum absolute difference between adjacent elements
12        for (int i = 0; i < arrayLength - 1; i++) {
13            int currentDifference = arr[i + 1] - arr[i];
14            minDifference = Math.min(minDifference, currentDifference);
15        }
16      
17        // Store all pairs with the minimum absolute difference
18        List<List<Integer>> result = new ArrayList<>();
19      
20        // Collect all pairs that have the minimum difference
21        for (int i = 0; i < arrayLength - 1; i++) {
22            if (arr[i + 1] - arr[i] == minDifference) {
23                // Add the pair to result list
24                result.add(List.of(arr[i], arr[i + 1]));
25            }
26        }
27      
28        return result;
29    }
30}
31
1class Solution {
2public:
3    vector<vector<int>> minimumAbsDifference(vector<int>& arr) {
4        // Sort the array to easily find consecutive differences
5        sort(arr.begin(), arr.end());
6      
7        // Initialize minimum difference to a large value (2^30)
8        int minDifference = 1 << 30;
9        int arraySize = arr.size();
10      
11        // First pass: find the minimum absolute difference between consecutive elements
12        for (int i = 0; i < arraySize - 1; ++i) {
13            int currentDifference = arr[i + 1] - arr[i];
14            minDifference = min(minDifference, currentDifference);
15        }
16      
17        // Store all pairs with the minimum absolute difference
18        vector<vector<int>> result;
19      
20        // Second pass: collect all pairs that have the minimum difference
21        for (int i = 0; i < arraySize - 1; ++i) {
22            if (arr[i + 1] - arr[i] == minDifference) {
23                // Add the pair to result (already in ascending order due to sorting)
24                result.push_back({arr[i], arr[i + 1]});
25            }
26        }
27      
28        return result;
29    }
30};
31
1/**
2 * Finds all pairs of elements with the minimum absolute difference in an array
3 * @param arr - The input array of numbers
4 * @returns Array of pairs with minimum absolute difference
5 */
6function minimumAbsDifference(arr: number[]): number[][] {
7    // Sort the array in ascending order
8    arr.sort((a, b) => a - b);
9  
10    // Initialize minimum difference with a large value (2^30)
11    let minDifference: number = 1 << 30;
12    const arrayLength: number = arr.length;
13  
14    // Find the minimum difference between consecutive elements
15    for (let i = 0; i < arrayLength - 1; i++) {
16        minDifference = Math.min(minDifference, arr[i + 1] - arr[i]);
17    }
18  
19    // Store all pairs that have the minimum difference
20    const result: number[][] = [];
21  
22    // Collect all pairs with the minimum difference
23    for (let i = 0; i < arrayLength - 1; i++) {
24        if (arr[i + 1] - arr[i] === minDifference) {
25            result.push([arr[i], arr[i + 1]]);
26        }
27    }
28  
29    return result;
30}
31

Time and Space Complexity

Time Complexity: O(n Γ— log n)

The time complexity is dominated by the sorting operation arr.sort(), which takes O(n Γ— log n) time where n is the length of the input array. After sorting, the code performs two linear passes through the array using pairwise(arr):

  • First pass to find the minimum difference: O(n-1) = O(n)
  • Second pass to collect pairs with minimum difference: O(n-1) = O(n)

Overall: O(n Γ— log n) + O(n) + O(n) = O(n Γ— log n)

Space Complexity: O(log n)

The space complexity consists of:

  • The sorting algorithm (Timsort in Python) uses O(log n) space for its recursive call stack
  • The pairwise iterator creates pairs on-the-fly without storing them all, using O(1) space
  • The output list is not counted as part of space complexity (it's the required output)
  • The variable mi uses O(1) space

Therefore, the dominant space usage comes from the sorting algorithm, giving us O(log n) space complexity.

Learn more about how to find time and space complexity quickly.

Common Pitfalls

Pitfall 1: Searching for minimum difference across all pairs (not just adjacent)

The Mistake: A common error is attempting to check all possible pairs in the array to find the minimum difference, leading to unnecessary O(nΒ²) comparisons:

# Inefficient approach - checking all pairs
min_diff = float('inf')
for i in range(len(arr)):
    for j in range(i + 1, len(arr)):
        min_diff = min(min_diff, abs(arr[j] - arr[i]))

Why it happens: It seems logical to check every possible pair since we want the "minimum absolute difference among all possible pairs."

The Solution: After sorting, the minimum absolute difference will always occur between adjacent elements. This is because for any three sorted numbers a < b < c, we have |b - a| < |c - a| and |c - b| < |c - a|. Therefore, we only need to check consecutive pairs:

arr.sort()
min_diff = float('inf')
for i in range(1, len(arr)):
    min_diff = min(min_diff, arr[i] - arr[i-1])

Pitfall 2: Forgetting to sort the array first

The Mistake:

# Wrong - trying to find pairs without sorting
result = []
min_diff = # ... find min diff somehow
for i in range(len(arr)):
    for j in range(i + 1, len(arr)):
        if abs(arr[j] - arr[i]) == min_diff:
            result.append([min(arr[i], arr[j]), max(arr[i], arr[j])])

Why it happens: The problem statement doesn't explicitly mention sorting, and one might think we need to preserve the original array order.

The Solution: Always sort first. The problem requires pairs in ascending order anyway, and sorting makes finding the minimum difference efficient:

arr.sort()  # Critical first step
# Now we can efficiently find min diff and pairs

Pitfall 3: Not handling the pair order correctly

The Mistake:

# Wrong - might add pairs in wrong order
if arr[i] - arr[i-1] == min_diff:
    result.append([arr[i], arr[i-1]])  # Wrong order!

Why it happens: After sorting, it's easy to forget that we need [smaller, larger] format for each pair.

The Solution: Since the array is sorted, arr[i-1] is always less than arr[i], so the correct order is:

result.append([arr[i-1], arr[i]])  # Correct: smaller element first
Discover Your Strengths and Weaknesses: Take Our 5-Minute Quiz to Tailor Your Study Plan:

Which of the following uses divide and conquer strategy?


Recommended Readings

Want a Structured Path to Master System Design Too? Don’t Miss This!

Load More