VOOZH about

URL: https://www.geeksforgeeks.org/dsa/queries-for-elements-greater-than-k-in-the-given-index-range-using-segment-tree/

⇱ Queries for elements greater than K in the given index range using Segment Tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Queries for elements greater than K in the given index range using Segment Tree

Last Updated : 12 Jul, 2025

Given an array arr[] of N elements and a number of queries where each query will contain three integers L, R, and K. For each query, the task is to find the number of elements in the subarray arr[L...R] which are greater than K.

Examples:

Input: arr[] = {7, 3, 9, 13, 5, 4}, q[] = {{0, 3, 6}, {1, 5, 8}} 
Output:


Query 1: Only 7, 9 and 13 are greater 
than 6 in the subarray {7, 3, 9, 13}. 
Query 2: Only 9 and 13 are greater 
than 8 in the subarray {3, 9, 13, 5, 4}.


Input: arr[] = {0, 1, 2, 3, 4, 5, 6, 7}, q[] = {{0, 7, 3}, {4, 6, 10}} 
Output:

Prerequisite:Segment tree

Naive approach: Find the answer for each query by simply traversing the array from index l till r and keep adding 1 to the count whenever the array element is greater than k

Below is the implementation of the above approach: 


Output:

3
2

Time Complexity: O(n * q)
Space Complexity: O(1)

Efficient approach: Build a Segment Tree with a vector at each node containing all the elements of the sub-range in sorted order. Answer each query using the segment tree where Binary Search can be used to calculate how many numbers are present in each node whose sub-range lies within the query range which is greater than K. Time complexity of this approach will be O(q * log(n) * log(n))

Below is the implementation of the above approach: 


Output
3
2

The space complexity of the segment tree is O(n log n). The tree has at most 4n nodes, and each node stores a vector of size at most n, which leads to the space complexity of O(n log n).

Another Approach:

Another way of doing it using segment trees is by storing the first element greater than in each node (if present) in that range, otherwise storing 0.

Here, we need to consider 3 cases for building the tree.

  1. If both left and right children contain a number other than 0, the answer is always the left child. (we need to consider the very first occurrence of the number greater than K.)
  2. If any one of the left or right child contains 0, the answer is always a number other than 0.
  3. If both left and right children contain 0, the answer is always 0 (indicating that no number greater than K is present in that range).

The query function remains the same as always.

Consider the following example:  arr[] = {7, 3, 9, 13, 5, 4} , K = 6

The tree in this case will look like this:

👁 Image

  Below is the implementation of the above approach:

Output:

7

Time Complexity: O(N * log N) to build the tree and O(log N) for each query.

Space Complexity: O(N)

Comment