VOOZH about

URL: https://www.geeksforgeeks.org/dsa/min-max-range-queries-array/

⇱ Min-Max Range Queries in Array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Min-Max Range Queries in Array

Last Updated : 23 Jul, 2025

Given an array arr[0 . . . n-1]. We need to efficiently find the minimum and maximum value from index qs (query start) to qe (query end) where 0 <= qs <= qe <= n-1. We are given multiple queries

Examples: 

Input: arr[] = {1, 8, 5, 9, 6, 14, 2, 4, 3, 7}, queries = 5

        qs = 0 qe = 4
        qs = 3 qe = 7
        qs = 1 qe = 6
        qs = 2 qe = 5
        qs = 0 qe = 8

Output: Minimum = 1 and Maximum = 9 
              Minimum = 2 and Maximum = 14 
              Minimum = 2 and Maximum = 14
              Minimum = 5 and Maximum = 14
              Minimum = 1 and Maximum = 14 

Input: arr[] = {2, 5, 3, 1, 8}, queries = 2

        qs = 2 qe = 3
        qs = 0 qe = 2

Output: Minimum = 1 and Maximum = 3 
              Minimum = 2 and Maximum = 5 

To solve the problem follow the below idea:

We solve this problem using the Tournament Method for each query.
The time complexity of this approach will be O(queries * n)

To solve the problem follow the below idea:

This problem can be solved more efficiently by using a Segment Tree

Below is the implementation of the above approach:


Output
Minimum = 1 and Maximum = 14 

Time Complexity: O(queries * log N)
Auxiliary Space: O(N)

Can we do better if there are no updates on the array? 

The above segment tree-based solution also allows array updates also to happen in O(Log n) time. Assume a situation when there are no updates (or the array is static). We can actually process all queries in O(1) time with some preprocessing. One simple solution is to make a 2D table of nodes that stores all ranges minimum and maximum. This solution requires O(1) query time but requires O(N2) preprocessing time and O(N2) extra space which can be a problem for large N. We can solve this problem in O(1) query time, O(n Log n) space and O(n Log n) preprocessing time using the Sparse Table.

This article is reviewed by team GeeksForGeeks. 


 

Comment