All problems
0967MediumArrayBinary SearchOrdered Set

Closest Pair at Least x Apart

Tracked in this browser only
Write code

Trains the technique from

LeetCode 2817Minimum Absolute Difference Between Elements With Constraint

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

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 is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

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