Skip to main content
Back to problems
Leetcode
Medium
Arrays
Matrices
Ordered Structures
Minimum Absolute Difference In Sliding Submatrix

Find the minimum absolute difference between any two distinct values inside every k×kk \times k submatrix, then return the smallest such difference across all windows.

Acceptance 100%
Problem Statement

Minimum Absolute Difference in Sliding Submatrix

You are given a 2D integer grid and an integer kk. Consider every contiguous k×kk \times k 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 k×kk \times k 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 grid with m rows and n columns
  • 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 k submatrices

Constraints

  • 1 <= m, n
  • 1 <= k <= min(m, n)
  • Grid values are integers
  • Only values inside a chosen k x k submatrix may be used
  • The answer is based on pairs of distinct values
Examples
Sample cases returned by the problem API.

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.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.