Skip to main content

Minimum Absolute Difference Between Elements With Constraint - Solution & Explanation

MediumArrayBinary SearchOrdered Set23 min readAsked at: Meta, Capital One, Visa +5
Practice this problem

Problem Statement

You are given a 0-indexed integer array nums and an integer x.

Find the minimum absolute difference between two elements in the array that are at least x indices apart.

In other words, find two indices i and j such that abs(i - j) >= x and abs(nums[i] - nums[j]) is minimized.

Return an integer denoting the minimum absolute difference between two elements that are at least x indices apart.

 

Example 1:

Input: nums = [4,3,2,4], x = 2
Output: 0
Explanation: We can select nums[0] = 4 and nums[3] = 4. 
They are at least 2 indices apart, and their absolute difference is the minimum, 0. 
It can be shown that 0 is the optimal answer.

Example 2:

Input: nums = [5,3,2,10,15], x = 1
Output: 1
Explanation: We can select nums[1] = 3 and nums[2] = 2.
They are at least 1 index apart, and their absolute difference is the minimum, 1.
It can be shown that 1 is the optimal answer.

Example 3:

Input: nums = [1,2,3,4], x = 3
Output: 3
Explanation: We can select nums[0] = 1 and nums[3] = 4.
They are at least 3 indices apart, and their absolute difference is the minimum, 3.
It can be shown that 3 is the optimal answer.

 

Constraints:

  • 1 <= nums.length <= 105
  • 1 <= nums[i] <= 109
  • 0 <= x < nums.length

Approach Overview

Problem Overview: You are given an integer array nums and an integer x. The goal is to find the minimum absolute difference between two elements nums[i] and nums[j] such that |i - j| ≥ x. The constraint prevents comparing nearby elements, so the algorithm must track only values that are far enough apart in the array.

Approach 1: Brute Force with Constraint Check (O(n²) time, O(1) space)

The straightforward approach checks every valid pair. Iterate through the array using two nested loops and only evaluate pairs where |i - j| ≥ x. For each valid pair, compute abs(nums[i] - nums[j]) and track the minimum. This method is simple and clearly demonstrates the constraint logic, but it performs up to comparisons and becomes impractical for large inputs.

Approach 2: Sliding Window with Sorted List (O(n log n) time, O(n) space)

The optimized approach maintains a dynamically sorted structure of eligible elements. As you iterate through the array, add the element nums[i - x] into an ordered structure once it becomes valid for comparison. This ensures every stored value satisfies the index distance constraint.

Use an ordered set or sorted list and locate the closest values to nums[i] using binary search. Specifically, find the first element greater than or equal to nums[i] and also check the previous element. These two candidates produce the smallest possible absolute difference in a sorted structure. Update the global minimum after each comparison.

The key insight: in a sorted structure, the nearest values to a number must lie directly adjacent in order. Binary search finds those candidates in O(log n), and insertion also costs O(log n) for balanced trees (or O(n) in Python lists but still efficient in practice). Iterating once through the array results in overall O(n log n) time.

Recommended for interviews: Start with the brute force idea to show you understand the constraint and pair comparison logic. Then move to the ordered-set solution. Interviewers typically expect the O(n log n) approach using a balanced tree, TreeSet, or sorted container because it demonstrates knowledge of binary search on dynamic data structures.

Approach 1: Sliding Window with Sorted List

This approach uses a sliding window along with a sorted data structure to efficiently find the minimum absolute difference between elements that are at least 'x' indices apart. As we iterate over the array, we maintain a sorted list of the last 'x' elements. For each element 'nums[i]', we calculate the difference with the closest elements in the sorted list and update the minimum difference accordingly. This method is efficient due to the sorted nature of the data structure, which allows quick access to the closest elements.

This solution uses the SortedList from the 'sortedcontainers' module for efficient insertion and access. As we iterate over elements in 'nums', we maintain a sliding window of the last 'x' elements in sorted order. For each element, we check adjacent elements from the sorted list to find the minimum difference and update our result.

Code

Python

Java

JavaScript

C++

C#

Complexity

Time Complexity: O(n log x), where n is the length of the array and x is the constraint for indices apart. Space Complexity: O(x) due to storing the elements in the sorted list.

Try this approach in the editor →

Approach 2: Brute Force with Constraint Check

A straightforward solution is to iterate through each pair of elements in 'nums' and compute their absolute difference if they meet the constraint |i - j| >= x. While this approach is simple and easy to implement, it is not optimal for large inputs as it runs in quadratic time. Despite its inefficiency, it can serve as a verification method for small inputs or in scenarios where performance constraints are relaxed.

This Python code loops through each permissible pair, checks if their index difference meets the constraint and calculates the absolute difference to find the minimum.

Code

Python

Java

JavaScript

C++

C#

Complexity

Time Complexity: O(n^2), as all pairs are checked. Space Complexity: O(1), as only simple variables are used.

Try this approach in the editor →

Approach 3: Ordered Set

We create an ordered set to store the elements whose distance to the current index is at least x.

Next, we enumerate from index i = x, each time we add nums[i - x] into the ordered set. Then we find the two elements in the ordered set which are closest to nums[i], and the minimum absolute difference between them is the answer.

The time complexity is O(n times log n), and the space complexity is O(n). Where n is the length of array nums.

Code

Python

Java

C++

Go

TypeScript

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Sliding Window with Sorted List

Time Complexity: O(n log x), where n is the length of the array and x is the constraint for indices apart. Space Complexity: O(x) due to storing the elements in the sorted list.

Brute Force with Constraint Check

Time Complexity: O(n^2), as all pairs are checked. Space Complexity: O(1), as only simple variables are used.

Ordered Set

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Brute Force with Constraint CheckO(n²)O(1)Good for understanding the constraint logic or very small arrays
Sliding Window with Sorted List / Ordered SetO(n log n)O(n)Best general solution; efficient for large inputs and typical interview expectations

Video Solution

2817. Minimum Absolute Difference Between Elements With Constraint (Leetcode Medium)Programming Live with Larry2,679 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Minimum Absolute Difference Between Elements With Constraint easy or hard?
The problem is rated Medium on LeetCode because the brute force idea is simple but inefficient. The challenge is recognizing that a dynamically maintained sorted structure enables fast nearest-value queries while respecting the index distance constraint.
Minimum Absolute Difference Between Elements With Constraint Python/Java solution
In Python, a sorted list with the bisect module can maintain ordered elements and perform binary search for neighbors. In Java, TreeSet provides built-in methods like ceiling() and floor() to quickly locate the closest values. Both implementations run in O(n log n) time.
How to solve Minimum Absolute Difference Between Elements With Constraint in O(n)?
A strict O(n) solution is generally not feasible because you must maintain ordering to find the closest numeric value efficiently. Most optimal implementations rely on a balanced tree, TreeSet, or sorted container with binary search, resulting in O(n log n) time.
What is the best approach for Minimum Absolute Difference Between Elements With Constraint?
The most efficient approach uses a sliding window with an ordered set or sorted list. While iterating through the array, insert elements that are at least x indices behind the current index. Use binary search to find the closest values to the current number in O(log n). This produces an overall time complexity of O(n log n) with O(n) space.
Is Minimum Absolute Difference Between Elements With Constraint asked at Google/Amazon/Meta?
Problems combining ordered sets, binary search, and sliding window techniques commonly appear in interviews at companies like Google, Amazon, and Meta. This question tests the ability to maintain a dynamically sorted structure while enforcing index constraints.
What data structure is used in Minimum Absolute Difference Between Elements With Constraint?
The optimal solution uses an ordered set or balanced binary search tree. Examples include TreeSet in Java, multiset in C++, or a sorted list with bisect in Python. These structures allow efficient insertion and nearest-value lookup using binary search.
What is the time complexity of Minimum Absolute Difference Between Elements With Constraint?
The brute force method runs in O(n²) time because it compares all valid pairs that satisfy the index constraint. The optimized ordered-set approach reduces the complexity to O(n log n) by maintaining a sorted structure and using binary search to find the closest values efficiently.

Ready to solve this problem?

Practice Minimum Absolute Difference Between Elements With Constraint with our built-in code editor and test cases.

Practice on FleetCode