VOOZH about

URL: https://www.geeksforgeeks.org/java/java-program-to-count-of-array-elements-greater-than-all-elements-on-its-left-and-at-least-k-elements-on-its-right/

⇱ Java Program to Count of Array elements greater than all elements on its left and at least K elements on its right - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Java Program to Count of Array elements greater than all elements on its left and at least K elements on its right

Last Updated : 23 Jul, 2025

Given an array A[ ] consisting of N distinct integers, the task is to find the number of elements which are strictly greater than all the elements preceding it and strictly greater than at least K elements on its right.

Examples:  

Input: A[] = {2, 5, 1, 7, 3, 4, 0}, K = 3 
Output:
Explanation: 
The only array elements satisfying the given conditions are: 

  • 5: Greater than all elements on its left {2} and at least K(= 3) elements on its right {1, 3, 4, 0}
  • 7: Greater than all elements on its left {2, 5, 1} and at least K(= 3) elements on its right {3, 4, 0}

Therefore, the count is 2.

Input: A[] = {11, 2, 4, 7, 5, 9, 6, 3}, K = 2 
Output:

Naive Approach: 
The simplest approach to solve the problem is to traverse the array and for each element, traverse all the elements on its left and check if all of them are smaller than it or not and traverse all elements on its right to check if at least K elements are smaller than it or not. For every element satisfying the conditions, increase count. Finally, print the value of count


Output
2

Time Complexity: O(N2
Auxiliary Space: O(1)

Efficient Approach: 
The above approach can be further optimized by using Self-Balancing BST. Follow the steps below:  

  • Traverse the array from right to left and insert all elements one by one in an AVL Tree
  • Using the AVL Tree generate an array countSmaller[] which contains the count of smaller elements on the right of every array element.
  • Traverse the array and for every ith element, check if it is the maximum obtained so far and countSmaller[i] is greater than or equal to K.
  • If so, increase count.
  • Print the final value of count as the answer.

Below is the implementation of the above approach: 

 
 


Output: 
2

 


 

Time Complexity: O(NlogN) 
Auxiliary Space: O(N)
 


Please refer complete article on Count of Array elements greater than all elements on its left and at least K elements on its right for more details!
 

Comment