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
Minimum Absolute Difference in Sliding Submatrix INPUT 3x3 Grid, k=2 1 2 3 4 5 6 7 8 9 2x2 sliding window grid = [[1,2,3], [4,5,6], [7,8,9]] k = 2 ALGORITHM STEPS 1 Slide Window Move k×k window across grid 2 Extract Values Get all values in submatrix 3 Sort Values Sort in ascending order 4 Compare Adjacent Find min diff between pairs Example: Top-left 2x2 Values: [1,2,4,5] Sorted: [1,2,4,5] Diffs: 2-1=1, 4-2=2, 5-4=1 Min diff = 1 FINAL RESULT Output: 2x2 Result Matrix 4 Sliding Windows Processed: [0,0]: [1,2,4,5] min=1 [0,1]: [2,3,5,6] min=1 [1,0]: [4,5,7,8] min=1 [1,1]: [5,6,8,9] min=1 Output Array 1 1 1 1 OK - [[1,1],[1,1]] Size: (3-2+1) x (3-2+1) Key Insight: Sorting k×k elements allows finding minimum absolute difference by only comparing adjacent pairs. After sorting, the minimum difference must be between consecutive elements (no need to check all pairs). Time complexity: O((m-k+1)(n-k+1) × k²log(k²)) where k² is the submatrix size. TutorialsPoint - Minimum Absolute Difference in Sliding Submatrix | Sort Then Compare Adjacent Approach
Asked in
Google 25 Amazon 18 Microsoft 12 Apple 8
23.4K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen