473. Find Minimum Difference Between Any Two Elements

EasyBinary SearchArraySortingBinary Search

Given an unsorted integer array nums, return the minimum absolute difference between any two distinct elements. Sort first, then use binary search or adjacent comparison.

Input: An integer array nums with at least 2 elements.

Output: Minimum absolute difference between any two distinct elements.

Examples

Example 1
Input: [1,5,3,19,18,25]
Output: 1
Explanation: Sorted: [1,3,5,18,19,25]. Min diff = |18-19|=1.
Example 2
Input: [30,5,20,9]
Output: 4
Explanation: Sorted: [5,9,20,30]. Min diff = |5-9|=4.
Example 3
Input: [1,10,20,30]
Output: 9
Explanation: Adjacent diffs: 9,10,10. Min=9.

Constraints

Asked by

TCSInfosysWiproCognizantCapgemini
Solve this problem in the editor →