[LeetCode] Minimum Absolute Difference in Sliding Submatrix

3567. Minimum Absolute Difference in Sliding Submatrix

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.

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
class Solution {
public:
vector<vector<int>> minAbsDiff(vector<vector<int>>& grid, int k) {
int n = grid.size(), m = grid[0].size();
vector<vector<int>> res;
for(int i = 0; i <= n - k; i++) {
res.emplace_back();
for(int j = 0; j <= m - k; j++) {
vector<int> S;
for(int ii = i; ii < i + k; ii++) {
for(int jj = j; jj < j + k; jj++) {
S.push_back(grid[ii][jj]);
}
}
sort(begin(S), end(S));
S.erase(unique(begin(S), end(S)), end(S));
if(S.size() == 1) res.back().push_back(0);
else {
int mi = INT_MAX;
for(int i = 1; i < S.size(); i++) {
mi = min(mi, S[i] - S[i-1]);
}
res.back().push_back(mi);
}
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2025/06/01/PS/LeetCode/minimum-absolute-difference-in-sliding-submatrix/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.