You are given an integer array nums and an integer k. Consider every contiguous window of length k in nums, from left to right.
For each window, compute the minimum absolute difference between two elements at distinct indices inside that window. If a window contains duplicate values, its answer is 0.
Return an array containing the answer for each window, in order from left to right. The result has length len(nums) - k + 1.
Function Signature
def min_abs_diff_windows(nums: list[int], k: int) -> list[int]:
...
Rules
-
The window that starts at index
i
is
nums[i:i + k]
, and its answer goes at index
i
of the result.
-
The two elements must sit at different indices of the window. An element is never paired with itself, but two equal values at different indices give
0
.
-
Each answer is a non-negative integer.
Constraints
-
2 <= k <= len(nums) <= 10^5
-
-10^9 <= nums[i] <= 10^9
Examples
Input: nums = [1,5,3,9,4], k = 3
Output: [2,2,1]
The windows are [1,5,3], [5,3,9] and [3,9,4]. Sorted, they are [1,3,5], [3,5,9] and [3,4,9], so the smallest differences are 2, 2 and 1.
Input: nums = [4,2,4,7,7], k = 2
Output: [2,2,3,0]
Each window holds one pair: [4,2] gives 2, [2,4] gives 2, [4,7] gives 3, and [7,7] holds the same value twice, so its answer is 0.
Input: nums = [-3,7,-1,10], k = 4
Output: [2]
There is one window. Sorted, it is [-3,-1,7,10], and the closest pair is -3 and -1, which are 2 apart.