Given an unsorted array, find the minimum difference between any pair in given array.
Example1.
Input: nums = [2, 4, 5, 9, 7]
Output: 1
Explanation: Difference between 5 and 4 is 1.
Expected Time Compelxity: O(N* log(N)) where N is length of array.
Expected Space Complexity: O(1)
1 Answer
3 years ago by VIPIN KUMAR
- At first sort the array. Then all the minimum differences will occur amoung the pairs of consecutive elements.
- Then iterate over the sorted array keeping track of the current minimum difference.
There is the answer.
Time Complextiy: O(nlogn) (sorting) + O(n) (iteration) = O(nlogn).
Optimal implementation wont use any extra space.
int solve(){
int nums[5] = {2,4,5,9,7};
sort(nums, nums+5);
int minDiff = INT_MAX;
for(ll i = 1; i < 5; i++)
minDiff = min(minDiff, nums[i]-nums[i-1]);
return minDiff;
}
3 years ago by 20AI026NamahJain