VOOZH about

URL: https://www.geeksforgeeks.org/dsa/2d-range-minimum-query-in-o1/

⇱ 2D Range Minimum Query in O(1) - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

2D Range Minimum Query in O(1)

Last Updated : 23 Jul, 2025

Given a matrix mat[][] of size N*M, the task is to find the minimum value in a submatrix of the array, defined by the top-left and bottom-right indices of the submatrix for the given queries.

Example:

Input: N = 4, M = 4, mat[][] = { { 5, 8, 2, 4 }, { 7, 2, 9, 1 }, { 1, 4, 7, 3 }, { 3, 5, 6, 8 } } 
queries[][] = {{0, 0, 3, 3}, {1, 1, 2, 2}}
Output:
1
2
Explanation: 
For first query, top-left corner at (0, 0) and bottom-right corner at (2, 2), which is the entire input matrix. The minimum value in this submatrix is 1.
For second call, the top-left corner at (1, 1) and bottom-right corner at (2, 2). The minimum value in this submatrix is 2.

One solution to this problem is to use a data structure called a sparse table. A sparse table is a data structure that allows you to perform RMQ in O(1) time after O(nmlogn*logm) preprocessing time.

To build a sparse table for a 2D array, you can follow these steps:

  • Preprocess the array to calculate the minimum value for each cell and for each submatrix with a size of 2k * 2l, where k and l are non-negative integers.
  • Store the minimum values in a 2D array called the sparse table. The size of the sparse table should be n*m*log(n)*log(m).
  • Firstly find the largest value of k such that 2k is less than or equal to the width of the submatrix.
  • Then, find the largest value of l such that 2l is less than or equal to the height of the submatrix. 
  • Using these values, you can look up the minimum value in the sparse table and return it as the result.

Here is a brief example of how to implement a 2D range minimum query using a sparse table in Python:


Output
1
2

Time complexity:

  • O(N * M * log(N) * log(M)) (To build sparse table)
  • O(1) (For Each Query)

Auxiliary Space: O(N * M * log(N) * log(M))

Related Articles:

Comment