Find the minimum absolute difference between any two distinct values inside every submatrix, then return the smallest such difference across all windows.
Minimum Absolute Difference in Sliding Submatrix
You are given a 2D integer grid and an integer . Consider every contiguous submatrix in the grid.
For each submatrix, look at all values contained in it and compute the minimum absolute difference between any two distinct elements.
Your task is to return the smallest such value across all submatrices.
If a submatrix has fewer than two distinct elements, its minimum absolute difference is not defined for that window, so it should be ignored when taking the overall minimum.
This problem asks you to efficiently evaluate overlapping submatrices rather than recomputing each window from scratch.
Input Format
Input
- An integer matrix
gridwithmrows andncolumns - An integer
k, the side length of each square submatrix
Output Format
Output
- Return a single integer: the minimum absolute difference found among all contiguous
k x ksubmatrices
Constraints
1 <= m, n1 <= k <= min(m, n)- Grid values are integers
- Only values inside a chosen
k x ksubmatrix may be used - The answer is based on pairs of distinct values
Example 1
Input
grid = [[1,5,3],[8,2,6],[4,7,9]], k = 2
Output
1
Explanation
The 2x2 submatrices contain values such as [1,5,8,2], [5,3,2,6], [8,2,4,7], and [2,6,7,9]. Their minimum absolute differences are 1, 1, 2, and 1 respectively, so the overall answer is 1.
Example 2
Input
grid = [[10,20,30],[40,50,60],[70,80,90]], k = 2
Output
10
Explanation
Every 2x2 submatrix contains numbers spaced by at least 10, so the minimum absolute difference across all windows is 10.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.