Skip to main content

Minimum Absolute Difference in Sliding Submatrix - Solution & Explanation

MediumArraySortingMatrix10 min readAsked at: Amazon, Google
Practice this problem

Problem Statement

You are given an m x n integer matrix grid and an integer k.

For every contiguous k x 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) x (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.

A submatrix (x1, y1, x2, y2) is a matrix that is formed by choosing all cells matrix[x][y] where x1 <= x <= x2 and y1 <= y <= y2.

 

Example 1:

Input: grid = [[1,8],[3,-2]], k = 2

Output: [[2]]

Explanation:

  • There is only one possible k x k submatrix: [[1, 8], [3, -2]].
  • Distinct values in the submatrix are [1, 8, 3, -2].
  • The minimum absolute difference in the submatrix is |1 - 3| = 2. Thus, the answer is [[2]].

Example 2:

Input: grid = [[3,-1]], k = 1

Output: [[0,0]]

Explanation:

  • Both k x k submatrix has only one distinct element.
  • Thus, the answer is [[0, 0]].

Example 3:

Input: grid = [[1,-2,3],[2,3,5]], k = 2

Output: [[1,2]]

Explanation:

  • There are two possible k × k submatrix:
    • Starting at (0, 0): [[1, -2], [2, 3]].
      • Distinct values in the submatrix are [1, -2, 2, 3].
      • The minimum absolute difference in the submatrix is |1 - 2| = 1.
    • Starting at (0, 1): [[-2, 3], [3, 5]].
      • Distinct values in the submatrix are [-2, 3, 5].
      • The minimum absolute difference in the submatrix is |3 - 5| = 2.
  • Thus, the answer is [[1, 2]].

 

Constraints:

  • 1 <= m == grid.length <= 30
  • 1 <= n == grid[i].length <= 30
  • -105 <= grid[i][j] <= 105
  • 1 <= k <= min(m, n)

Approach Overview

Problem Overview: You are given a matrix and a fixed submatrix size k × k. For every possible sliding submatrix, compute the minimum absolute difference between any two elements inside that window. The result for each position depends only on the values contained in that specific k × k region.

Approach 1: Brute Force Pair Comparison (O((m−k+1)(n−k+1) · k⁴) time, O(1) space)

For each valid top‑left corner of a k × k window, enumerate all elements in that submatrix. Compare every pair of values and track the smallest absolute difference. A k × k window contains numbers, so pairwise comparison requires O(k⁴) operations per window. This approach uses constant extra space but becomes slow when k grows because the number of pair comparisons increases quadratically. It mainly serves as a conceptual baseline that proves the problem can be solved by direct enumeration.

Approach 2: Enumeration + Sorting (O((m−k+1)(n−k+1) · k² log(k²)) time, O(k²) space)

A more efficient observation: the minimum absolute difference among numbers always appears between two adjacent elements after sorting. For each sliding k × k region, first collect its values into a temporary list. Sort the list using a standard comparison sort. Then iterate once through the sorted values and compute abs(a[i] - a[i-1]) to find the smallest gap. Sorting costs O(k² log(k²)), and the linear scan adds O(k²). Because there are (m−k+1)(n−k+1) windows, this becomes the dominant complexity.

The algorithm relies heavily on sequential traversal of the matrix (a common pattern in matrix problems) and temporary containers for each window. Sorting simplifies the difference calculation since only adjacent values must be checked instead of every pair. Most implementations store the window values in an array or vector, apply a built‑in sort, then scan once to compute the minimum gap.

This method fits naturally with problems involving value comparisons in arrays and ordering via sorting. It trades extra memory and sorting cost for a dramatic reduction in pair comparisons.

Recommended for interviews: Start by describing the brute‑force pair comparison to demonstrate understanding of the requirement. Then move to the sorted enumeration approach. Interviewers expect the key insight that the minimum absolute difference must appear between adjacent elements after sorting. Implementing that idea clearly shows comfort with matrix traversal, temporary buffers, and algorithmic optimization.

Solution

We can enumerate all possible k times k submatrices by their top-left coordinates (i, j). For each submatrix, we extract all its elements into a list nums. Then, we sort nums and compute the absolute differences between adjacent distinct elements to find the minimum absolute difference. Finally, we store the result in a 2D array.

The time complexity is O((m - k + 1) times (n - k + 1) times k^2 log(k)), where m and n are the number of rows and columns of the matrix, and k is the size of the submatrix. The space complexity is O(k^2), used to store the elements of each submatrix.

Code

Python

Java

C++

Go

TypeScript

Rust

Try this approach in the editor →

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Brute Force Pair ComparisonO((m−k+1)(n−k+1) · k⁴)O(1)Conceptual baseline or when k is extremely small
Enumeration + SortingO((m−k+1)(n−k+1) · k² log(k²))O(k²)General case; efficient because sorting reduces pair comparisons to adjacent checks

Video Solution

Minimum Absolute Difference in Sliding Submatrix | Straight Forward | Leetcode 3567 | MIKcodestorywithMIK7,095 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Minimum Absolute Difference in Sliding Submatrix easy or hard?
The problem is typically classified as Medium. Matrix traversal is straightforward, but recognizing that sorting allows checking only adjacent differences is the key optimization that reduces the brute-force pair comparison cost.
Minimum Absolute Difference in Sliding Submatrix Python/Java solution
Most implementations follow the same pattern: iterate over every valid top-left corner of the k × k window, collect values into an array, sort it, then compute the smallest adjacent difference. The logic is identical across Python, Java, C++, Go, and other languages.
How to solve Minimum Absolute Difference in Sliding Submatrix in O(n)?
A strict O(n) solution is generally not feasible because each sliding submatrix must examine k² elements. The common optimization reduces pairwise comparisons by sorting the window values and checking only adjacent elements, giving O(k² log(k²)) per window rather than O(k⁴).
What is the best approach for Minimum Absolute Difference in Sliding Submatrix?
The practical solution enumerates each k × k submatrix, stores its k² elements, sorts them, and checks adjacent differences. Sorting ensures the minimum absolute difference appears between neighboring values. The complexity is O((m−k+1)(n−k+1) · k² log(k²)) with O(k²) extra space.
Is Minimum Absolute Difference in Sliding Submatrix asked at Google/Amazon/Meta?
Matrix window problems combined with sorting or difference calculations appear frequently in large tech company interviews. Variants involving sliding windows in matrices, minimum differences, and ordered comparisons are commonly discussed at companies like Google, Amazon, and Meta.
What data structure is used in Minimum Absolute Difference in Sliding Submatrix?
The core data structure is a temporary array or list that stores the k² elements from each submatrix. After collecting the values, a sorting algorithm orders them so the minimum difference can be found by scanning adjacent elements.
What is the time complexity of Minimum Absolute Difference in Sliding Submatrix?
Using the optimized enumeration + sorting approach, each k × k window requires O(k² log(k²)) time for sorting and O(k²) for scanning. With (m−k+1)(n−k+1) sliding positions, the total time complexity becomes O((m−k+1)(n−k+1) · k² log(k²)). Space complexity is O(k²).

Ready to solve this problem?

Practice Minimum Absolute Difference in Sliding Submatrix with our built-in code editor and test cases.

Practice on FleetCode