Show problems as
Classic problem #2817MediumArrayBinary SearchOrdered Set

Minimum Absolute Difference Between Elements With Constraint

Real-world version: Closest Pair at Least x Apart
Tracked in this browser only
Read Minimum Absolute Difference Between Elements With Constraint on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

Readings are given as nums, along with a gap x.

Consider the pairs of positions i and j that sit at least x apart, that is where the difference of the positions is at least x. Return the smallest difference in value between the readings of any such pair, taken without sign.

A gap of 0 allows a position to be paired with itself, which gives a difference of nothing.

Examples

Example 1

Input
nums = [14, 3, 27, 9, 41, 6], x = 3
Output
3

Positions three or more apart include 0 with 3, whose readings are 14 and 9, five apart, and 2 with 5, whose readings are 27 and 6. The closest such pair is the first.

Example 2

Input
nums = [5, 9], x = 0
Output
0

With a gap of nothing a position pairs with itself, so the answer is nothing.

Example 3

Input
nums = [1, 2, 3, 4], x = 3
Output
3

Only the two ends are three apart, and their readings differ by three.

Constraints

  • 1 <= nums.length <= 10^5
  • 1 <= nums[i] <= 10^9
  • 0 <= x <= nums.length - 1

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def min_absolute_difference(nums: list[int], x: int) -> int:
Java
public int minAbsoluteDifference(int[] nums, int x)