Mid/SeniorArrayPrefix Sum

Minimum Absolute Difference Queries

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.

You are given an integer array nums and the array queries where queries[i] = [li, ri]. For each query i, compute the minimum absolute difference of the subarray nums[li...ri] containing the elements of nums between the 0-based indices li and ri (inclusive).

Return an array ans where ans[i] is the answer to the i^th query.

A subarray is a contiguous sequence of elements in an array.

The value of |x| is defined as:

  • x if x >= 0.
  • -x if x < 0.
Example 1
Inputnums = [1,3,4,8], queries = [[0,1],[1,2],[2,3],[0,3]]
Output[2,1,4,1]
For the queried subarrays [1,3], [3,4], [4,8], and [1,3,4,8], the minimum absolute differences are 2, 1, 4, and 1 respectively.
Example 2
Inputnums = [4,5,2,2,7,10], queries = [[2,3],[0,2],[0,5],[3,5]]
Output[-1,1,1,3]
The first queried subarray has all equal elements, while the remaining queried subarrays have minimum absolute differences 1, 1, and 3 respectively.

Constraints

  • 2 <= nums.length <= 10^5
  • 1 <= nums[i] <= 100
  • 1 <= queries.length <= 2 * 10^4
  • 0 <= li < ri < nums.length

Asked at 1 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate