#1200
Minimum Absolute Difference
EasyArraySortingSortingArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
By sorting the array first, we can ensure that the minimum absolute difference will always be between consecutive elements. This allows us to reduce the number of comparisons significantly.
⚙️
Algorithm
5 steps- 1Step 1: Sort the array.
- 2Step 2: Initialize a variable to store the minimum difference as infinity.
- 3Step 3: Iterate through the sorted array and calculate the absolute difference between each consecutive pair.
- 4Step 4: Update the minimum difference and store pairs that match this minimum difference.
- 5Step 5: Return the list of pairs.
solution.py17 lines
1# Full working Python code
2
3def minimumAbsDifference(arr):
4 arr.sort()
5 min_diff = float('inf')
6 pairs = []
7 for i in range(len(arr) - 1):
8 diff = arr[i + 1] - arr[i]
9 if diff < min_diff:
10 min_diff = diff
11 pairs = [[arr[i], arr[i + 1]]]
12 elif diff == min_diff:
13 pairs.append([arr[i], arr[i + 1]])
14 return pairs
15
16# Example usage
17print(minimumAbsDifference([4,2,1,3]))ℹ
Complexity note: The time complexity is O(n log n) due to the sorting step. The space complexity is O(n) because we store the pairs in a list.
- 1Sorting the array allows us to find the minimum difference between consecutive elements.
- 2Pairs must be stored in ascending order, which is naturally handled by the sorting step.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.