![]() |
VOOZH | about |
Given an unsorted array, find the minimum difference between any pair in the given array.
Examples :
Input: [1, 5, 3, 19, 18, 25]
Output: 1
Explanation: Minimum difference is between 18 and 19Input: [30, 5, 20, 9]
Output: 4
Explanation: Minimum difference is between 5 and 9Input: [1, 19, -4, 31, 38, 25, 100]
Output: 5
Explanation: Minimum difference is between 1 and -4
Table of Content
The idea is to compare every possible pair of elements in the array and calculate their absolute differenceand keep track of the minimum diff.
Minimum difference is 1
The idea is to first sort the array so that elements with the smallest difference become adjacent to each other. After sorting, instead of checking all possible pairs, we only compare consecutive elements. This works because the minimum difference in a sorted array will always occur between neighboring elements, making the approach much more efficient.
Minimum difference is 1