Leetcode #1906: Minimum Absolute Difference Queries
In this guide, we solve Leetcode #1906 Minimum Absolute Difference Queries in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
The minimum absolute difference of an array a is defined as the minimum value of |a[i] - a[j]|, where 0 <= i < j < a.length and a[i] != a[j]. If all elements of a are the same, the minimum absolute difference is -1.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Array, Hash Table
Intuition
Fast membership checks and value lookups are the heart of this problem, which makes a hash map the natural choice.
By storing what we have already seen (or counts/indexes), we can answer the question in one pass without backtracking.
Approach
Scan the input once, using the map to detect when the condition is satisfied and to update state as you go.
This keeps the solution linear while remaining easy to explain in an interview setting.
Steps:
- Initialize a hash map for seen items or counts.
- Iterate through the input, querying/updating the map.
- Return the first valid result or the final computed value.
Example
Input: nums = [1,3,4,8], queries = [[0,1],[1,2],[2,3],[0,3]]
Output: [2,1,4,1]
Explanation: The queries are processed as follows:
- queries[0] = [0,1]: The subarray is [1,3] and the minimum absolute difference is |1-3| = 2.
- queries[1] = [1,2]: The subarray is [3,4] and the minimum absolute difference is |3-4| = 1.
- queries[2] = [2,3]: The subarray is [4,8] and the minimum absolute difference is |4-8| = 4.
- queries[3] = [0,3]: The subarray is [1,3,4,8] and the minimum absolute difference is |3-4| = 1.
Python Solution
class Solution:
def minDifference(self, nums: List[int], queries: List[List[int]]) -> List[int]:
m, n = len(nums), len(queries)
pre_sum = [[0] * 101 for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, 101):
t = 1 if nums[i - 1] == j else 0
pre_sum[i][j] = pre_sum[i - 1][j] + t
ans = []
for i in range(n):
left, right = queries[i][0], queries[i][1] + 1
t = inf
last = -1
for j in range(1, 101):
if pre_sum[right][j] - pre_sum[left][j] > 0:
if last != -1:
t = min(t, j - last)
last = j
if t == inf:
t = -1
ans.append(t)
return ans
Complexity
The time complexity is O(n). The space complexity is O(n).
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.