VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-elements-that-are-greater-than-at-least-k-elements-on-its-left-and-right/

⇱ Count elements that are greater than at least K elements on its left and right - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count elements that are greater than at least K elements on its left and right

Last Updated : 23 Jul, 2025

Given an array arr[] of size n (1 <= n <= 10^5) and a positive integer k, the task is to count all indices i ( 1<= i < n) in the array such that at least k elements to the left of i and at least k elements to the right of i, which are strictly smaller than the value at the ith index (i.e, arr[i]).

Example:

Input:arr = {1,3,6,5,2,1}, k = 2
Output: 2
Explanation: The elements marked in bold are only valid indices, arr = {2,3,6,5,2,3}

Input: arr = {2,2,2}, k = 3
Output: 0

Approach:

The idea is to choose some specific data structure which will keep track of maximum. so that we can check if current index i is greater than maximum element to the left. Lets see about the core idea.

We'll use Max heap data structure and always maintain its size to be k. For any index i, we'll check if current value at i (i.e, arr[i]) is greater than the max heap top element, it means there must me at least k elements to the left of i which are less than current value. If current value is less than the max heap's top then we have to remove the max heap top and insert current element into the heap as this will help us in more reducing the maximum value so it will help other future element while validating. We'll keep track of this validation in left[] array.

We'll do the above same from right to left and keep track of validation in right[] array.

Finally, we'll travel in both array and check if left[i] == 1 or true && right[i] == 1 or true then this is valid index. So, increment our count.

Steps-by-step approach:

  • Initialize two priority queues maxH and maxH2 to track the k largest elements, and create vectors for left[] and right[] indices.
  • Iterate through the array from left to right, updating the priority queue and marking elements satisfying conditions on the left[].
  • Iterate through the array from right to left, updating the second priority queue and marking elements satisfying conditions on the right[].
  • Count the number of elements satisfying conditions (left[i] == 1 or true && right[i] == 1 or true) on both sides.
  • Return the count as the result.

Below is the implementation of the above approach:


Output
2

Time Complexity: O(n log (n))
Auxiliary Space: O(k)

Related Article: Count of Array elements greater than all elements on its left and at least K elements on its right

Comment