Welcome to Subscribe On Youtube

Formatted question description: https://leetcode.ca/all/1906.html

1906. Minimum Absolute Difference Queries

Level

Medium

Description

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.

  • For example, the minimum absolute difference of the array [5,2,3,7,2] is |2 - 3| = 1. Note that it is not 0 because a[i] and a[j] must be different.

You are given an integer array nums and the array queries where queries[i] = [l_i, r_i]. For each query i, compute the minimum absolute difference of the subarray nums[l_i...r_i] containing the elements of nums between the 0-based indices l_i and r_i (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:

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.

Example 2:

Input: nums = [4,5,2,2,7,10], queries = [[2,3],[0,2],[0,5],[3,5]]

Output: [-1,1,1,3]

Explanation: The queries are processed as follows:

  • queries[0] = [2,3]: The subarray is [2,2] and the minimum absolute difference is -1 because all the elements are the same.
  • queries[1] = [0,2]: The subarray is [4,5,2] and the minimum absolute difference is 4-5 = 1.
  • queries[2] = [0,5]: The subarray is [4,5,2,2,7,10] and the minimum absolute difference is 4-5 = 1.
  • queries[3] = [3,5]: The subarray is [2,7,10] and the minimum absolute difference is 7-10 = 3.

Constraints:

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

Solution

Since the number range of nums is limited, store the number of occurrences for each number from 1 to 100 for each prefix of nums. Then for each query, the number of occurrences for each number from 1 to 100 in the query range can be calculated efficiently, and the minimum absolute difference can be calculated by looping over the numbers from 1 to 100 and calculating the differences between each paif of adjacent numbers that both occur in the range.

  • class Solution {
        public int[] minDifference(int[] nums, int[][] queries) {
            Map<Integer, int[]> map = new HashMap<Integer, int[]>();
            int length = nums.length;
            int[] counts = new int[101];
            for (int i = 0; i < length; i++) {
                int num = nums[i];
                counts[num]++;
                int[] copy = new int[101];
                System.arraycopy(counts, 0, copy, 0, 101);
                map.put(i, copy);
            }
            int queriesCount = queries.length;
            int[] ans = new int[queriesCount];
            for (int i = 0; i < queriesCount; i++) {
                int[] query = queries[i];
                int[] rangeCounts = getRangeCounts(map, query[0], query[1]);
                int curMin = Integer.MAX_VALUE;
                int prev = -1;
                for (int j = 1; j <= 100; j++) {
                    if (rangeCounts[j] > 0) {
                        if (prev > 0) {
                            int diff = j - prev;
                            curMin = Math.min(curMin, diff);
                        }
                        prev = j;
                    }
                }
                ans[i] = curMin == Integer.MAX_VALUE ? -1 : curMin;
            }
            return ans;
        }
    
        public int[] getRangeCounts(Map<Integer, int[]> map, int start, int end) {
            int[] endCounts = map.get(end);
            if (start == 0)
                return endCounts;
            int[] prevCounts = map.get(start - 1);
            int[] rangeCounts = new int[101];
            for (int i = 0; i <= 100; i++)
                rangeCounts[i] = endCounts[i] - prevCounts[i];
            return rangeCounts;
        }
    }
    
    ############
    
    class Solution {
        public int[] minDifference(int[] nums, int[][] queries) {
            int m = nums.length, n = queries.length;
            int[][] preSum = new int[m + 1][101];
            for (int i = 1; i <= m; ++i) {
                for (int j = 1; j <= 100; ++j) {
                    int t = nums[i - 1] == j ? 1 : 0;
                    preSum[i][j] = preSum[i - 1][j] + t;
                }
            }
    
            int[] ans = new int[n];
            for (int i = 0; i < n; ++i) {
                int left = queries[i][0], right = queries[i][1] + 1;
                int t = Integer.MAX_VALUE;
                int last = -1;
                for (int j = 1; j <= 100; ++j) {
                    if (preSum[right][j] > preSum[left][j]) {
                        if (last != -1) {
                            t = Math.min(t, j - last);
                        }
                        last = j;
                    }
                }
                if (t == Integer.MAX_VALUE) {
                    t = -1;
                }
                ans[i] = t;
            }
            return ans;
        }
    }
    
  • 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
    
    ############
    
    # 1906. Minimum Absolute Difference Queries
    # https://leetcode.com/problems/minimum-absolute-difference-queries
    
    class Solution:
        def minDifference(self, nums: List[int], queries: List[List[int]]) -> List[int]:
            dp = [[0] * (max(nums) + 1)]
            
            for i, x in enumerate(nums):
                t = dp[-1][:]
                t[x] += 1
                dp.append(t)
            
            res = []
            for start, end in queries:
                A = [i for i, (a,b) in enumerate(zip(dp[start], dp[end + 1])) if a != b]
                res.append(min([b - a for a,b in zip(A, A[1:])] or [-1]))
                
            return res
    
    
  • class Solution {
    public:
        vector<int> minDifference(vector<int>& nums, vector<vector<int>>& queries) {
            int m = nums.size(), n = queries.size();
            int preSum[m + 1][101];
            for (int i = 1; i <= m; ++i) {
                for (int j = 1; j <= 100; ++j) {
                    int t = nums[i - 1] == j ? 1 : 0;
                    preSum[i][j] = preSum[i - 1][j] + t;
                }
            }
    
            vector<int> ans(n);
            for (int i = 0; i < n; ++i) {
                int left = queries[i][0], right = queries[i][1] + 1;
                int t = 101;
                int last = -1;
                for (int j = 1; j <= 100; ++j) {
                    if (preSum[right][j] > preSum[left][j]) {
                        if (last != -1) {
                            t = min(t, j - last);
                        }
                        last = j;
                    }
                }
                if (t == 101) {
                    t = -1;
                }
                ans[i] = t;
            }
            return ans;
        }
    };
    
  • func minDifference(nums []int, queries [][]int) []int {
    	m, n := len(nums), len(queries)
    	preSum := make([][101]int, m+1)
    	for i := 1; i <= m; i++ {
    		for j := 1; j <= 100; j++ {
    			t := 0
    			if nums[i-1] == j {
    				t = 1
    			}
    			preSum[i][j] = preSum[i-1][j] + t
    		}
    	}
    
    	ans := make([]int, n)
    	for i := 0; i < n; i++ {
    		left, right := queries[i][0], queries[i][1]+1
    		t, last := 101, -1
    		for j := 1; j <= 100; j++ {
    			if preSum[right][j]-preSum[left][j] > 0 {
    				if last != -1 {
    					if t > j-last {
    						t = j - last
    					}
    				}
    				last = j
    			}
    		}
    		if t == 101 {
    			t = -1
    		}
    		ans[i] = t
    	}
    	return ans
    }
    
  • function minDifference(nums: number[], queries: number[][]): number[] {
        let m = nums.length,
            n = queries.length;
        let max = 100;
        // let max = Math.max(...nums);
        let pre: number[][] = [];
        pre.push(new Array(max + 1).fill(0));
        for (let i = 0; i < m; ++i) {
            let num = nums[i];
            pre.push(pre[i].slice());
            pre[i + 1][num] += 1;
        }
    
        let ans = [];
        for (let [left, right] of queries) {
            let last = -1;
            let min = Infinity;
            for (let j = 1; j < max + 1; ++j) {
                if (pre[left][j] < pre[right + 1][j]) {
                    if (last != -1) {
                        min = Math.min(min, j - last);
                    }
                    last = j;
                }
            }
            ans.push(min == Infinity ? -1 : min);
        }
        return ans;
    }
    
    

All Problems

All Solutions