#1906

Minimum Absolute Difference Queries

Medium
ArrayPrefix SumHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

By leveraging sorting and a set to track unique elements, we can efficiently find the minimum absolute difference without checking every pair. This approach reduces the number of comparisons needed.

⚙️

Algorithm

5 steps
  1. 1Step 1: For each query, extract the subarray defined by the indices l and r.
  2. 2Step 2: Use a set to store unique elements from the subarray.
  3. 3Step 3: Sort the unique elements to easily find the minimum difference between consecutive elements.
  4. 4Step 4: Iterate through the sorted unique elements to find the minimum absolute difference.
  5. 5Step 5: If there are less than two unique elements, return -1; otherwise, return the minimum difference found.
solution.py15 lines
1# Full working Python code
2
3def min_absolute_difference(nums, queries):
4    results = []
5    for l, r in queries:
6        subarray = nums[l:r+1]
7        unique_elements = sorted(set(subarray))
8        if len(unique_elements) < 2:
9            results.append(-1)
10            continue
11        min_diff = float('inf')
12        for i in range(1, len(unique_elements)):
13            min_diff = min(min_diff, unique_elements[i] - unique_elements[i - 1])
14        results.append(min_diff)
15    return results

Complexity note: The time complexity is O(n log n) due to the sorting step, while the space complexity is O(n) for storing unique elements.

  • 1Using a set to track unique elements can significantly reduce the number of comparisons needed.
  • 2Sorting the unique elements allows for efficient calculation of minimum differences.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.