Leetcode 1200. Minimum Absolute Difference
Given an array of distinct integers arr
, find all pairs of elements with the minimum absolute difference of any two elements. Specifically, these pairs should be listed in ascending order based on their values, and each pair should be in the format [a, b]
where a < b
.
For simplicity, I will assume that:
If these assumptions hold, we’ll proceed with the solution.
import java.util.*;
public class MinimumAbsoluteDifference {
public List<List<Integer>> minimumAbsDifference(int[] arr) {
// Sort the array
Arrays.sort(arr);
// Initialize the list to store the result
List<List<Integer>> result = new ArrayList<>();
// Find the minimum absolute difference
int minDiff = Integer.MAX_VALUE;
for (int i = 1; i < arr.length; i++) {
int diff = arr[i] - arr[i - 1];
if (diff < minDiff) {
minDiff = diff;
}
}
// Collect the pairs with minimum absolute difference
for (int i = 1; i < arr.length; i++) {
int diff = arr[i] - arr[i - 1];
if (diff == minDiff) {
List<Integer> pair = new ArrayList<>();
pair.add(arr[i - 1]);
pair.add(arr[i]);
result.add(pair);
}
}
return result;
}
// Example driver method for testing
public static void main(String[] args) {
MinimumAbsoluteDifference mad = new MinimumAbsoluteDifference();
int[] arr = {4, 2, 1, 3};
System.out.println(mad.minimumAbsDifference(arr)); // Output: [[1, 2], [2, 3], [3, 4]]
}
}
Thus, the overall time complexity is dominated by the sorting step, making it O(n \log n).
This solution is efficient for the input size constraints and ensures correctness by leveraging simpler problem transformations like sorting.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?