Program to Find Out the Minimal Submatrices in Python

Suppose we have a 2D matrix and another value k. Our goal is to return a matrix that contains the minimum values of all k x k sub-matrices.

So, if the input is like ?

3 5 6
8 6 5
4 3 12

and k = 2, then the output will be [[3, 5], [3, 3]].

Understanding the Problem

From the input, we can see that the top left submatrix has the minimum value of 3 ?

3 5
8 6

The top right submatrix has the minimum value of 5 ?

5 6
6 5

The bottom left submatrix has the minimum value of 3 ?

8 6
4 3

The bottom right submatrix has the minimum value of 3 ?

6 5
3 12

Algorithm Approach

To solve this efficiently, we use a sliding window approach with a deque (double−ended queue) to find minimum values in linear time ?

  • For each row, find minimum values in k−sized windows using a deque
  • For each column, find minimum values in k−sized windows using a deque
  • Extract the final result matrix from processed values

Implementation

import collections

class Solution:
    def solve(self, matrix, k):
        # Step 1: Process each row to find minimum in k-sized windows
        for r, row in enumerate(matrix):
            q = collections.deque()
            nrow = []
            for i in range(len(row)):
                # Remove elements outside current window
                if q and q[0] == i - k:
                    q.popleft()
                # Remove elements larger than current element
                while q and row[q[-1]] > row[i]:
                    q.pop()
                q.append(i)
                nrow.append(row[q[0]])
            matrix[r] = nrow
        
        # Step 2: Process each column to find minimum in k-sized windows
        for j in range(len(matrix[0])):
            q = collections.deque()
            ncol = []
            for i in range(len(matrix)):
                # Remove elements outside current window
                if q and q[0] == i - k:
                    q.popleft()
                # Remove elements larger than current element
                while q and matrix[q[-1]][j] > matrix[i][j]:
                    q.pop()
                q.append(i)
                ncol.append(matrix[q[0]][j])
            # Update column values
            for i in range(len(matrix)):
                matrix[i][j] = ncol[i]
        
        # Step 3: Extract result matrix
        ret = [[0] * (len(matrix[0]) - k + 1) for _ in range(len(matrix) - k + 1)]
        for i in range(len(ret)):
            for j in range(len(ret[0])):
                ret[i][j] = matrix[i + k - 1][j + k - 1]
        return ret

# Test the solution
ob = Solution()
matrix = [
    [3, 5, 6],
    [8, 6, 5],
    [4, 3, 12]
]
result = ob.solve(matrix, 2)
print(result)
[[3, 5], [3, 3]]

How It Works

The algorithm uses a sliding window maximum/minimum technique with deques ?

  1. Row Processing: For each row, maintain a deque storing indices of potential minimum elements in the current k−sized window
  2. Column Processing: Similarly process each column to find minimum values in k−sized vertical windows
  3. Result Extraction: The final result matrix contains minimum values from all k x k submatrices

Time Complexity

The time complexity is O(m × n) where m and n are the dimensions of the matrix. Each element is processed at most twice (once for row processing and once for column processing).

Conclusion

This efficient algorithm uses sliding window technique with deques to find minimum values in all k x k submatrices. The approach processes rows first, then columns, achieving optimal O(m × n) time complexity.

Updated on: 2026-03-25T13:54:10+05:30

339 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements