Minimum Absolute Difference in Sliding Submatrix - Problem
You are given an m × n integer matrix grid and an integer k.
For every contiguous k × 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) × (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.
Input & Output
Example 1 — Basic 3×3 Grid with k=2
$
Input:
grid = [[1,2,3],[4,5,6],[7,8,9]], k = 2
›
Output:
[[1,1],[1,1]]
💡 Note:
Four 2×2 submatrices: top-left [[1,2],[4,5]] has min diff = min(|1-2|,|1-4|,|1-5|,|2-4|,|2-5|,|4-5|) = 1, top-right [[2,3],[5,6]] has min diff = 1, bottom-left [[4,5],[7,8]] has min diff = 1, bottom-right [[5,6],[8,9]] has min diff = 1
Example 2 — Same Values
$
Input:
grid = [[1,1,1],[1,1,1],[1,1,1]], k = 2
›
Output:
[[0,0],[0,0]]
💡 Note:
All elements are identical, so minimum absolute difference is 0 for all 2×2 submatrices
Example 3 — Single Submatrix
$
Input:
grid = [[1,5],[3,7]], k = 2
›
Output:
[[2]]
💡 Note:
Only one 2×2 submatrix: [[1,5],[3,7]]. Check pairs: |1-5|=4, |1-3|=2, |1-7|=6, |5-3|=2, |5-7|=2, |3-7|=4. Minimum is 2
Constraints
- m == grid.length
- n == grid[i].length
- 1 ≤ k ≤ min(m, n)
- 1 ≤ grid[i][j] ≤ 109
Visualization
Tap to expand
Understanding the Visualization
1
Input Grid
3×3 matrix with k=2 sliding window
2
Extract Submatrices
Find all possible 2×2 submatrices
3
Compute Results
Calculate minimum difference for each submatrix
Key Takeaway
🎯 Key Insight: Minimum absolute difference in any set of numbers occurs between adjacent elements when sorted
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code