DEV Community

Cover image for πŸ“ Beginner-Friendly Guide 'Minimum Absolute Difference' - Problem 1200 (C++, Python, JavaScript)
Om Shree
Om Shree

Posted on

πŸ“ Beginner-Friendly Guide 'Minimum Absolute Difference' - Problem 1200 (C++, Python, JavaScript)

Finding the closest relationship between numbers is a fundamental task in data analysis and pattern recognition. This problem challenges you to efficiently identify pairs of numbers that sit nearest to each other on a number line.

You're given:

  • An array of distinct integers named arr.

Your goal:

  • Find all pairs of elements that have the minimum absolute difference of any two elements in the array.
  • Return these pairs in ascending order, where each pair satisfies .

Intuition: The Power of Sorting

If we look at a random pile of numbers, finding the two closest ones requires comparing every single number with every other number. This would take time. However, if we line the numbers up in order (sorting), the closest neighbors must be physically next to each other.

By sorting the array first:

  1. We only need to check the difference between adjacent elements: arr[i] and arr[i+1].
  2. As we iterate through the sorted list, we track the smallest difference found so far.
  3. If we find a new, smaller difference, we throw away our old results and start a new list.
  4. If we find a difference equal to our current minimum, we add that pair to our collection.

Walkthrough: Understanding the Examples

Example 1: arr = [4, 2, 1, 3]

  1. Sort the array: [1, 2, 3, 4].
  2. First gap: (2 - 1) = 1. Current minDiff is 1. Results: [[1, 2]].
  3. Second gap: (3 - 2) = 1. Matches minDiff. Results: [[1, 2], [2, 3]].
  4. Third gap: (4 - 3) = 1. Matches minDiff. Results: [[1, 2], [2, 3], [3, 4]].
  5. Final Output: [[1, 2], [2, 3], [3, 4]].

C++ Solution

class Solution {
public:
    vector<vector<int>> minimumAbsDifference(vector<int>& arr) {
        vector<vector<int>> res;
        sort(arr.begin(), arr.end());

        // Initialize with a large value or the first possible difference
        int minDiff = arr[1] - arr[0];

        for (int i = 0; i < arr.size() - 1; i++) {
            int currDiff = arr[i+1] - arr[i];

            if (currDiff < minDiff) {
                // Found a new smaller gap: reset the list
                minDiff = currDiff;
                res.clear();
                res.push_back({arr[i], arr[i+1]});
            } else if (currDiff == minDiff) {
                // Matches the current smallest gap: add to list
                res.push_back({arr[i], arr[i+1]});
            }
        }
        return res;
    }
};

Enter fullscreen mode Exit fullscreen mode

Python Solution

class Solution:
    def minimumAbsDifference(self, arr: list[int]) -> list[list[int]]:
        arr.sort()
        res = []
        min_diff = float('inf')

        for i in range(len(arr) - 1):
            curr_diff = arr[i+1] - arr[i]

            if curr_diff < min_diff:
                # Update minimum and start a new results list
                min_diff = curr_diff
                res = [[arr[i], arr[i+1]]]
            elif curr_diff == min_diff:
                # Add to existing results
                res.append([arr[i], arr[i+1]])

        return res

Enter fullscreen mode Exit fullscreen mode

JavaScript Solution

/**
 * @param {number[]} arr
 * @return {number[][]}
 */
var minimumAbsDifference = function(arr) {
    // Sort numerically in ascending order
    arr.sort((a, b) => a - b);

    let res = [];
    let minDiff = Infinity;

    for (let i = 0; i < arr.length - 1; i++) {
        let currDiff = arr[i+1] - arr[i];

        if (currDiff < minDiff) {
            minDiff = currDiff;
            res = [[arr[i], arr[i+1]]];
        } else if (currDiff === minDiff) {
            res.push([arr[i], arr[i+1]]);
        }
    }

    return res;
};

Enter fullscreen mode Exit fullscreen mode

Key Takeaways

  • Sorting for Proximity: Sorting is the most efficient way to bring "closest" values together, reducing our search space significantly.
  • Greedy Refinement: By clearing the result list when a smaller difference is found, we use a greedy approach to ensure only the global minimums are kept.
  • Time Complexity: The performance is dominated by the sorting step, resulting in time complexity.

Final Thoughts

This problem is a classic example of how changing the state of data (sorting) makes an impossible-looking task simple. In real-world systems, this logic is used in Recommendation Engines to find items with the most similar attributes or in Signal Processing to find the closest frequency peaks. Mastering these "sorting-first" patterns is a major milestone in your interview preparation journey.

Top comments (0)