Skip to content

1200. Minimum Absolute Difference 👍

  • Time: $O(\texttt{sort})$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
 public:
  vector<vector<int>> minimumAbsDifference(vector<int>& arr) {
    vector<vector<int>> ans;
    int mn = INT_MAX;

    ranges::sort(arr);

    for (int i = 1; i < arr.size(); ++i) {
      const int diff = arr[i] - arr[i - 1];
      if (diff < mn) {
        mn = diff;
        ans.clear();
      }
      if (diff == mn)
        ans.push_back({arr[i - 1], arr[i]});
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
  public List<List<Integer>> minimumAbsDifference(int[] arr) {
    List<List<Integer>> ans = new ArrayList<>();
    int mn = Integer.MAX_VALUE;

    Arrays.sort(arr);

    for (int i = 1; i < arr.length; ++i) {
      final int diff = arr[i] - arr[i - 1];
      if (diff < mn) {
        mn = diff;
        ans.clear();
      }
      if (diff == mn)
        ans.add(Arrays.asList(arr[i - 1], arr[i]));
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution:
  def minimumAbsDifference(self, arr: list[int]) -> list[list[int]]:
    ans = []
    mn = math.inf

    arr.sort()

    for a, b in itertools.pairwise(arr):
      diff = b - a
      if diff < mn:
        mn = diff
        ans = []
      if diff == mn:
        ans.append([a, b])

    return ans