VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-of-subarrays-of-given-array-with-median-at-least-x/

⇱ Count of Subarrays of given Array with median at least X - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count of Subarrays of given Array with median at least X

Last Updated : 23 Jul, 2025

Given an array arr[]of integers with length N and an integer X, the task is to calculate the number of subarrays with median greater than or equal to the given integer X.

Examples:

Input: N=4, A = [5, 2, 4, 1], X = 4
Output: 7
Explanation: For subarray [5], median is 5. (>= 4)
For subarray [5, 2], median is 5.  (>= 4)
For subarray [5, 2, 4], median is 4. (>= 4)
For subarray [5, 2, 4, 1], median is 4. (>= 4)
For subarray [2, 4], median is 4. (>= 4)
For subarray [4], median is 4. (>= 4)
For subarray [4, 1], median is 4. (>= 4)

Input: N = [3, 7, 2, 0, 1, 5], X = 10
Output: 0
Explanation: There are no subarrays with median greater than or equal to X.

Approach:  The problem can be solved based on the following idea.

To find a subarray with median greater or equal to X at least half of the elements should be greater than or equal to X.

Follow the below steps to implement the above idea:

  • Replace each element of an array with 1 if it is greater than or equal to X, else replace it with -1.
  • Based on the above idea, for the new array, median of any subarray to be greater than or equal to X, its sum of elements should be greater than or equal to 0.
  • For calculating the number of subarray with a sum greater than or equal to 0:
    • Find prefix sum up to each index of the new array.
    • Traverse the newly created prefix array starting from index 1 and calculate the number of elements before it with a value less than or equal to the current value.
    • Add all those in the final answer as they will also form a subarray with the current one satisfying all conditions.
    • After finding it for an index, add the current value to a multiset.
  • Return the final answer.

Note: For efficiently calculating the number of elements with a value less than or equal to Y, use policy-based data structures.

Below is the implementation of the above approach:


Output
7

Time Complexity: O(N * logN)
Auxiliary Space: O(N)

Comment