3567. Minimum Absolute Difference in Sliding Submatrix
Description
You are given an m x n
integer matrix grid
and an integer k
.
For every contiguous k x k
submatrix of grid
, compute the minimum absolute difference between any two distinct values within that submatrix.
Return a 2D array ans
of size (m - k + 1) x (n - k + 1)
, where ans[i][j]
is the minimum absolute difference in the submatrix whose top-left corner is (i, j)
in grid
.
Note: If all elements in the submatrix have the same value, the answer will be 0.
A submatrix (x1, y1, x2, y2)
is a matrix that is formed by choosing all cells matrix[x][y]
where x1 <= x <= x2
and y1 <= y <= y2
.
Example 1:
Input: grid = [[1,8],[3,-2]], k = 2
Output: [[2]]
Explanation:
- There is only one possible
k x k
submatrix:[[1, 8], [3, -2]]
. - Distinct values in the submatrix are
[1, 8, 3, -2]
. - The minimum absolute difference in the submatrix is
|1 - 3| = 2
. Thus, the answer is[[2]]
.
Example 2:
Input: grid = [[3,-1]], k = 1
Output: [[0,0]]
Explanation:
- Both
k x k
submatrix has only one distinct element. - Thus, the answer is
[[0, 0]]
.
Example 3:
Input: grid = [[1,-2,3],[2,3,5]], k = 2
Output: [[1,2]]
Explanation:
- There are two possible
k × k
submatrix:- Starting at
(0, 0)
:[[1, -2], [2, 3]]
.- Distinct values in the submatrix are
[1, -2, 2, 3]
. - The minimum absolute difference in the submatrix is
|1 - 2| = 1
.
- Distinct values in the submatrix are
- Starting at
(0, 1)
:[[-2, 3], [3, 5]]
.- Distinct values in the submatrix are
[-2, 3, 5]
. - The minimum absolute difference in the submatrix is
|3 - 5| = 2
.
- Distinct values in the submatrix are
- Starting at
- Thus, the answer is
[[1, 2]]
.
Constraints:
1 <= m == grid.length <= 30
1 <= n == grid[i].length <= 30
-105 <= grid[i][j] <= 105
1 <= k <= min(m, n)
Solutions
Solution 1: Enumeration
We can enumerate all possible \(k \times k\) submatrices by their top-left coordinates \((i, j)\). For each submatrix, we extract all its elements into a list \(\textit{nums}\). Then, we sort \(\textit{nums}\) and compute the absolute differences between adjacent distinct elements to find the minimum absolute difference. Finally, we store the result in a 2D array.
The time complexity is \(O((m - k + 1) \times (n - k + 1) \times k^2 \log(k))\), where \(m\) and \(n\) are the number of rows and columns of the matrix, and \(k\) is the size of the submatrix. The space complexity is \(O(k^2)\), used to store the elements of each submatrix.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
|