Complete-Preparation

🎉 One-stop destination for all your technical interview Preparation 🎉

View the Project on GitHub

1200. Minimum Absolute Difference 🌟

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

Brute force

Sort + Two traversal

class Solution {
public:
    vector<vector<int>> minimumAbsDifference(vector<int>& arr)
    {
        sort(arr.begin(), arr.end());
        int minDiff = INT_MAX;
        int n = arr.size();
        for (int i = 0; i < n - 1; i++) {
            if (arr[i + 1] - arr[i] < minDiff)
                minDiff = arr[i + 1] - arr[i];
        }
        vector<vector<int>> ans;

        for (int i = 0; i < n - 1; i++) {
            if (arr[i + 1] - arr[i] == minDiff)
                ans.push_back({ arr[i], arr[i + 1] });
        }

        return ans;
    }
};