Minimum Absolute Difference in Sliding Submatrix - Problem
Imagine you're analyzing data patterns in a grid where you need to find the closest values within every possible square window of size k x k.
Given an m x n integer matrix grid and an integer k, your task is to:
- Examine every contiguous
k x ksubmatrix within the grid - For each submatrix, find the minimum absolute difference between any two distinct values
- Return a 2D result array where each position represents the minimum difference for the submatrix starting at that position
Key Points:
- If all elements in a submatrix are identical, the minimum difference is
0 - The result matrix has dimensions
(m - k + 1) x (n - k + 1) - Each result position
[i][j]corresponds to the submatrix with top-left corner at(i, j)
Example: For a 4x4 grid with k=2, you'll have 9 different 2x2 submatrices to analyze, resulting in a 3x3 answer matrix.
Input & Output
example_1.py — Basic 3×3 Matrix
$
Input:
grid = [[1,2,3],[4,5,6],[7,8,9]], k = 2
›
Output:
[[1,1],[1,1]]
💡 Note:
For k=2, we have four 2×2 submatrices. Top-left [1,2,4,5] has min diff 1 (between 1&2 or 4&5). 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.py — 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 the minimum absolute difference in any submatrix is 0.
example_3.py — Large Differences
$
Input:
grid = [[1,10,100],[2,20,200],[3,30,300]], k = 2
›
Output:
[[1,10],[1,10]]
💡 Note:
Each 2×2 submatrix contains values with different ranges, but the minimum differences are consistently small due to adjacent row/column values.
Constraints
- 1 ≤ k ≤ min(m, n) ≤ 100
- 1 ≤ grid[i][j] ≤ 105
- The matrix must be large enough to contain at least one k×k submatrix
Visualization
Tap to expand
Understanding the Visualization
1
Position Window
Place k×k sliding window at each valid position in matrix
2
Extract Values
Collect all k² elements from current submatrix window
3
Sort & Compare
Sort extracted values and check only consecutive pairs
4
Record Minimum
Store the minimum difference found in result matrix
Key Takeaway
🎯 Key Insight: After sorting elements, minimum absolute difference can only occur between consecutive values, dramatically reducing the search space from all pairs to adjacent pairs only.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code