Learner Level

Implement the minimumDifferencePairSorted method that returns the smallest difference between any pair after sorting.

The input contains an integer array nums and its length size. Your task is to find the smallest absolute difference between any two different elements in the array.

The pair can be formed from any two positions. After sorting the array, the minimum difference will always be found between two neighboring values.

For example, in [4,2,1,3], the sorted values are [1,2,3,4], and the smallest difference is 1.

Example 1
Input:
nums (int[]) = [4,2,1,3]
size (int) = 4
Return:
(int) 1
Example 2
Input:
nums (int[]) = [1,3,6,10,15]
size (int) = 5
Return:
(int) 2
Example 3
Input:
nums (int[]) = [9,4,1,7]
size (int) = 4
Return:
(int) 2

Sort the array first so that close values come next to each other.

Once the values are sorted, there is no need to compare every possible pair. The smallest difference must be between two adjacent elements, because any element farther away in sorted order will only create an equal or larger difference.

Scan the sorted array once, calculate the difference between each neighboring pair, and keep the smallest value found.

Pseudocode:

function minimumDifferencePairSorted(nums, size):
    if size < 2:
        return 0
    sort nums in ascending order
    best = absolute(nums[1] - nums[0])
    for i from 2 to size - 1:
        difference = absolute(nums[i] - nums[i - 1])
        if difference < best:
            best = difference
    return best
Run your code to see the result.