VOOZH about

URL: https://www.geeksforgeeks.org/dsa/length-of-longest-subarray-in-which-elements-greater-than-k-are-more-than-elements-not-greater-than-k/

⇱ Longest Subarray with Majority Greater than K - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Longest Subarray with Majority Greater than K

Last Updated : 24 Feb, 2026

Given an array arr[] and an integer k, Find the length of the longest subarray in which the number of elements greater than k is more than the number of elements less than or equal to k.

Examples:

Input: arr[] = [1, 2, 3, 4, 1], k = 2
Output:
Explanation: The subarray [2, 3, 4] or [3, 4, 1] satisfy the given condition, and there is no subarray of length 4 or 5 which will hold the given condition, so the answer is 3.

Input: arr[] = [6, 5, 3, 4], k = 2
Output: 4
Explanation: In the subarray [6, 5, 3, 4], there are 4 elements > 2 and 0 elements <= 2, so it is the longest subarray.  

[Naive Approach] - Iterating over all Subarrays - O(n2) Time and O(1) Space

The idea is to iterate over all subarrays while keeping a count of elements greater than k and count of elements smaller than k. For every element greater than k, increment the counter by 1 and for every element less than or equal to k, decrement the counter by 1. The longest subarray having counter > 0 will be the final answer.


Output
3

[Expected Approach] - Using Hashing - O(n) Time and O(n) Space

Converting all elements greater than k to +1 and all elements less than or equal to k to -1. Now, the problem reduces to finding the length of the longest subarray with a positive sum in this modified array.

How to find the length of longest subarray with sum > 0?

We use sum - 1 in the map to find an earlier prefix where the balance of good ( >k ) vs bad ( <=k ) elements was just one less than the current balance. This ensures that the subarray between that earlier point and the current index has a net positive count of good elements. If the current `sum` is not positive, we can’t directly say the subarray is valid, so we search for a prefix with sum = sum - 1.


Output
3
Comment