DEV Community

loading...

LeetCode 1200. Minimum Absolute Difference (javascript solution)

cod3pineapple profile image codingpineapple ・1 min read

Description:

Given an array of distinct integers arr, find all pairs of elements with the minimum absolute difference of any two elements.

Return a list of pairs in ascending order(with respect to pairs), each pair [a, b] follows

a, b are from arr
a < b
b - a equals to the minimum absolute difference of any two elements in arr

Solution:

Time Complexity : O(n)
Space Complexity: O(n)

var minimumAbsDifference = function(arr) {
    const ans = [];
    // Put smallest numbers first
    arr.sort((a, b) => a - b);
    // minDiff should be changed on the first iteration
    let minDiff = Infinity;
    for (let i = 1; i < arr.length; i++) {
        // The new minDiff changes if the current diff is smaller
        minDiff = Math.min(minDiff, arr[i] - arr[i - 1]);
    }
    for (let i = 1; i < arr.length; i++) {
        // Push all pairs that equal the minDiff into ans
        if (arr[i] - arr[i - 1] === minDiff) ans.push([arr[i - 1], arr[i]]);
    }
    return ans;
};
Enter fullscreen mode Exit fullscreen mode

Discussion (0)

Forem Open with the Forem app