Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Longest subarray in which all elements are greater than K
Next article icon

Longest Subarray having Majority Elements Greater Than K

Last Updated : 28 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

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

Examples:

Input: arr[]= [1, 2, 3, 4, 1], k = 2
Output: 3 
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.  

Table of Content

  • [Naive Approach] Iterating over all Subarrays - O(n^2) Time and O(1) Space
  • [Expected Approach] Using Hashing - O(n) Time and O(n) Space

[Naive Approach] Iterating over all Subarrays - O(n^2) 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.

C++
// C++ Code to find the length of longest subarray  // in which count of elements > k is more than count  // of elements < k by iterating over all subarrays #include <bits/stdc++.h> using namespace std; int longestSubarray(vector<int> &arr, int k) {     int n = arr.size();     int res = 0;        // Traverse through all subarrays    for (int i = 0; i < n; i++) {                int cnt = 0;        for (int j = i; j < n; j++) {            if(arr[j] > k)                cnt++;            else                cnt--;                      // Update result with the maximum length            if(cnt > 0)                res = max(res, j - i + 1);        }    }    return res; }  int main() { 	vector<int> arr = {1, 2, 3, 4, 1};     int k = 2;  	cout << longestSubarray(arr, k); 	return 0; } 
C
// C Code to find the length of longest subarray  // in which count of elements > k is more than count  // of elements < k by iterating over all subarrays #include <stdio.h>  int longestSubarray(int arr[], int n, int k) {     int res = 0;      // Traverse through all subarrays     for (int i = 0; i < n; i++) {         int cnt = 0;         for (int j = i; j < n; j++) {             if (arr[j] > k)                 cnt++;             else                 cnt--;              // Update result with the maximum length             if (cnt > 0 && res < (j - i + 1))                 res = (j - i + 1);         }     }     return res; }  int main() {     int arr[] = {1, 2, 3, 4, 1};     int k = 2;     int n = sizeof(arr) / sizeof(arr[0]);      printf("%d\n", longestSubarray(arr, n, k));     return 0; } 
Java
// Java Code to find the length of longest subarray  // in which count of elements > k is more than count  // of elements < k by iterating over all subarrays import java.util.*;  class GfG {     static int longestSubarray(int[] arr, int k) {         int n = arr.length;         int res = 0;          // Traverse through all subarrays         for (int i = 0; i < n; i++) {             int cnt = 0;             for (int j = i; j < n; j++) {                 if (arr[j] > k)                     cnt++;                 else                     cnt--;                  // Update result with the maximum length                 if (cnt > 0)                     res = Math.max(res, j - i + 1);             }         }         return res;     }      public static void main(String[] args) {         int[] arr = {1, 2, 3, 4, 1};         int k = 2;          System.out.println(longestSubarray(arr, k));     } } 
Python
# Python Code to find the length of longest subarray  # in which count of elements > k is more than count  # of elements < k by iterating over all subarrays  def longestSubarray(arr, k):     n = len(arr)     res = 0      # Traverse through all subarrays     for i in range(n):         cnt = 0         for j in range(i, n):             if arr[j] > k:                 cnt += 1             else:                 cnt -= 1              # Update result with the maximum length             if cnt > 0:                 res = max(res, j - i + 1)          return res  if __name__ == "__main__":     arr = [1, 2, 3, 4, 1]     k = 2     print(longestSubarray(arr, k)) 
C#
// C# Code to find the length of longest subarray  // in which count of elements > k is more than count  // of elements < k by iterating over all subarrays using System; using System.Collections.Generic;  class GfG {     static int longestSubarray(int[] arr, int k) {         int n = arr.Length;         int res = 0;          // Traverse through all subarrays         for (int i = 0; i < n; i++) {             int cnt = 0;             for (int j = i; j < n; j++) {                 if (arr[j] > k)                     cnt++;                 else                     cnt--;                  // Update result with the maximum length                 if (cnt > 0)                     res = Math.Max(res, j - i + 1);             }         }         return res;     }      static void Main() {         int[] arr = {1, 2, 3, 4, 1};         int k = 2;          Console.WriteLine(longestSubarray(arr, k));     } } 
JavaScript
// JavaScript Code to find the length of longest subarray  // in which count of elements > k is more than count  // of elements < k by iterating over all subarrays  function longestSubarray(arr, k) {     let n = arr.length;     let res = 0;      // Traverse through all subarrays     for (let i = 0; i < n; i++) {         let cnt = 0;         for (let j = i; j < n; j++) {             if (arr[j] > k)                 cnt++;             else                 cnt--;              // Update result with the maximum length             if (cnt > 0)                 res = Math.max(res, j - i + 1);         }     }     return res; }  // Driver Code let arr = [1, 2, 3, 4, 1]; let k = 2;  console.log(longestSubarray(arr, k)); 

Output
3

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

The idea is to first transform the array, 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 compute the prefix sum of the transformed array where elements are +1 or -1, so the sum stays in range [-n, +n]. A hash map prefIdx tracks the first occurrence of each prefix sum. By storing the earliest index of each sum, we can efficiently find the longest subarray with positive sum using hash map lookup.

Steps to implement the above idea:

  • Convert all elements greater than k to +1 and those less than or equal to k to -1.
  • At each index, calculate the prefix sum s, which will lie in the range [-n, +n].
  • Use a hash map prefIdx to store the first index at which each prefix sum value appears.
  • Iterate through the range -n to +n and update prefIdx[i] to store the minimum index seen so far. This enables fast lookup for smaller prefix values.
  • While iterating again, for each index i with prefix sum s, use prefIdx[s - 1] to find the left-most index where prefix sum is smaller.
  • For such an index i, compute the length as i - prefIdx[s - 1]. Track the maximum among all such values and return it.
C++
// C++ Code to find the length of longest subarray // in which count of elements > k is more than count // of elements < k using hash map #include <bits/stdc++.h> using namespace std;  int longestSubarray(vector<int> &arr, int k) {     int n = arr.size();     unordered_map<int, int> prefIdx;     int sum = 0, res = 0;      // Traverse through all subarrays     for (int i = 0; i < n; i++) {          // Consider arr[i] <= k as -1 and arr[i] > k as +1         sum += (arr[i] > k ? 1 : -1);          // make an entry for sum if it is not present         // in the hash map         if (prefIdx.find(sum) == prefIdx.end())             prefIdx[sum] = i;     }        // If all elements are smaller than k, return 0     if(prefIdx.find(-n) != prefIdx.end())         return 0;    	prefIdx[-n] = n;        // For each sum i, update prefIdx[i] with      // min(prefIdx[-n], prefIdx[-n+1] .... pref[i])     for(int i = -n + 1; i <= n; i++) {         if(prefIdx.find(i) == prefIdx.end())             prefIdx[i] = prefIdx[i - 1];         else             prefIdx[i] = min(prefIdx[i], prefIdx[i - 1]);     }          // To find the longest subarray with sum > 0 ending at i,     // we need left-most occurrence of s' such that s' < s.     sum = 0;     for(int i = 0; i < n; i++) {     	sum += (arr[i] > k ? 1 : -1);         if(sum > 0)             res = i + 1;         else         	res = max(res, i - prefIdx[sum - 1]);     }     return res; }  int main() {     vector<int> arr = {1, 2, 3, 4, 1};     int k = 2;      cout << longestSubarray(arr, k);     return 0; } 
Java
// Java Code to find the length of longest subarray // in which count of elements > k is more than count // of elements < k using hash map import java.util.HashMap; import java.util.Map;  class GfG {          static int longestSubarray(int[] arr, int k) {                  int n = arr.length;         Map<Integer, Integer> prefIdx = new HashMap<>();         int sum = 0, res = 0;          // Traverse through all elements         for (int i = 0; i < n; i++) {              // Consider arr[i] <= k as -1 and arr[i] > k as +1             sum += (arr[i] > k ? 1 : -1);              // make an entry for sum if it is not present             // in the hash map             if (!prefIdx.containsKey(sum))                 prefIdx.put(sum, i);         }                  // If all elements are smaller than k, return 0         if (prefIdx.containsKey(-n))             return 0;                prefIdx.put(-n, n);          // For each sum i, update prefIdx[i] with         // min(prefIdx[-n], prefIdx[-n+1] .... pref[i])         for (int i = -n + 1; i <= n; i++) {             if (!prefIdx.containsKey(i))                 prefIdx.put(i, prefIdx.get(i - 1));             else                 prefIdx.put(i, Math.min(prefIdx.get(i),                                          prefIdx.get(i - 1)));         }          // To find the longest subarray with sum > 0 ending at i,         // we need left-most occurrence of s' such that s' < s.         sum = 0;         for (int i = 0; i < n; i++) {             sum += (arr[i] > k ? 1 : -1);             if(sum > 0)                 res = i + 1;             else              	res = Math.max(res, i - prefIdx.get(sum - 1));         }          return res;     }      public static void main(String[] args) {         int[] arr = {1, 2, 3, 4, 1};         int k = 2;          System.out.println(longestSubarray(arr, k));     } } 
Python
# Python Code to find the length of longest subarray # in which count of elements > k is more than count # of elements < k using dictionary  def longestSubarray(arr, k):     n = len(arr)     prefIdx = {}     sum = 0     res = 0      # Traverse through all subarrays     for i in range(n):         # Consider arr[i] <= k as -1 and arr[i] > k as +1         sum += 1 if arr[i] > k else -1          # make an entry for sum if it is not present         # in the hash map         if sum not in prefIdx:             prefIdx[sum] = i  	# If all elements are smaller than k, return 0     if -n in prefIdx:         return 0     prefIdx[-n] = n      # For each sum i, update prefIdx[i] with      # min(prefIdx[-n], prefIdx[-n+1] .... pref[i])     for i in range(-n + 1, n + 1):         if i not in prefIdx:             prefIdx[i] = prefIdx[i - 1]         else:             prefIdx[i] = min(prefIdx[i], prefIdx[i - 1])      # To find the longest subarray with sum > 0 ending at i,     # we need left-most occurrence of s' such that s' < s.     sum = 0     for i in range(n):         sum += 1 if arr[i] > k else -1         if sum > 0:             res = i + 1         else:         	res = max(res, i - prefIdx[sum - 1])      return res  if __name__ == "__main__":     arr = [1, 2, 3, 4, 1]     k = 2     print(longestSubarray(arr, k)) 
C#
// C# Code to find the length of longest subarray // in which count of elements > k is more than count // of elements < k using hash map using System; using System.Collections.Generic;  class GfG {     static int LongestSubarray(int[] arr, int k) {                  int n = arr.Length;         Dictionary<int, int> prefIdx = new Dictionary<int, int>();         int sum = 0, res = 0;          // Traverse through all subarrays         for (int i = 0; i < n; i++) {                        // Consider arr[i] <= k as -1 and arr[i] > k as +1             sum += (arr[i] > k ? 1 : -1);              // make an entry for sum if it is not present             // in the hash map             if (!prefIdx.ContainsKey(sum))                 prefIdx[sum] = i;         }          // If all elements are smaller than k, return 0         if (prefIdx.ContainsKey(-n)) {             return 0;         }                  prefIdx[-n] = n;          // For each sum i, update prefIdx[i] with          // min(prefIdx[-n], prefIdx[-n+1] .... pref[i])         for (int i = -n + 1; i <= n; i++) {             if (!prefIdx.ContainsKey(i))                 prefIdx[i] = prefIdx[i - 1];             else                 prefIdx[i] = Math.Min(prefIdx[i], prefIdx[i - 1]);         }          // To find the longest subarray with sum > 0 ending at i,         // we need left-most occurrence of s' such that s' < s.         sum = 0;         for (int i = 0; i < n; i++) {             sum += (arr[i] > k ? 1 : -1);             if(sum > 0)                 res = i + 1;             else             	res = Math.Max(res, i - prefIdx[sum - 1]);         }         return res;     }      static void Main() {         int[] arr = new int[] { 1, 2, 3, 4, 1 };         int k = 2;          Console.WriteLine(LongestSubarray(arr, k));     } } 
JavaScript
// JavaScript Code to find the length of longest subarray // in which count of elements > k is more than count // of elements < k using hash map  function longestSubarray(arr, k) {     let n = arr.length;     let prefIdx = new Map();     let sum = 0, res = 0;      // Traverse through all subarrays     for (let i = 0; i < n; i++) {          // Consider arr[i] <= k as -1 and arr[i] > k as +1         sum += (arr[i] > k ? 1 : -1);          // make an entry for sum if it is not present         // in the hash map         if (!prefIdx.has(sum)) {             prefIdx.set(sum, i);         }     }      // If all elements are smaller than k, return 0     if (prefIdx.has(-n)) {         return 0;     }          prefIdx.set(-n, n);      // For each sum i, update prefIdx[i] with      // min(prefIdx[-n], prefIdx[-n+1] .... pref[i])     for (let i = -n + 1; i <= n; i++) {         if (!prefIdx.has(i)) {             prefIdx.set(i, prefIdx.get(i - 1));         } else {             prefIdx.set(i, Math.min(prefIdx.get(i), prefIdx.get(i - 1)));         }     }      // To find the longest subarray with sum > 0 ending at i,     // we need left-most occurrence of s' such that s' < s.     sum = 0;     for (let i = 0; i < n; i++) {         sum += (arr[i] > k ? 1 : -1);         if (sum > 0)         	res = i + 1;         else         	res = Math.max(res, i - prefIdx.get(sum - 1));     }     return res; }  // Driver Code let arr = [1, 2, 3, 4, 1]; let k = 2;  console.log(longestSubarray(arr, k)); 

Output
3

Next Article
Longest subarray in which all elements are greater than K

S

souradeep
Improve
Article Tags :
  • Analysis of Algorithms
  • Searching
  • DSA
  • Arrays
  • Binary Search
Practice Tags :
  • Arrays
  • Binary Search
  • Searching

Similar Reads

  • Longest subarray with elements having equal modulo K
    Given an integer K and an array arr of integer elements, the task is to print the length of the longest sub-array such that each element of this sub-array yields same remainder upon division by K. Examples: Input: arr[] = {2, 1, 5, 8, 1}, K = 3 Output: 2 {2, 1, 5, 8, 1} gives remainders {2, 1, 2, 2,
    10 min read
  • Longest subarray not having more than K distinct elements
    Given N elements and a number K, find the longest subarray which has not more than K distinct elements.(It can have less than K). Examples: Input : arr[] = {1, 2, 3, 4, 5} k = 6 Output : 1 2 3 4 5 Explanation: The whole array has only 5 distinct elements which is less than k, so we print the array i
    8 min read
  • Longest subarray in which all elements are greater than K
    Given an array of N integers and a number K, the task is to find the length of the longest subarray in which all the elements are greater than K. Examples: Input: a[] = {3, 4, 5, 6, 7, 2, 10, 11}, K = 5 Output: 2 There are two possible longest subarrays of length 2. They are {6, 7} and {10, 11}. Inp
    6 min read
  • Longest subarray having average greater than or equal to x
    Given an array of integers and an integer x. Find the length of maximum size subarray having an average of integers greater than or equal to x. Examples: Input : arr[] = {-2, 1, 6, -3}, x = 3Output : 2Longest subarray is {1, 6} having average3.5 greater than x = 3.Input : arr[] = {2, -3, 3, 2, 1}, x
    14 min read
  • Largest subarray having sum greater than k
    Given an array of integers and a value k, the task is to find the length of the largest subarray having a sum greater than k. Examples: Input: arr[] = [-2, 1, 6, -3], k = 5Output: 2Explanation: The largest subarray with a sum greater than 5 is {1, 6}. Input: arr[] = [2, -3, 3, 2, 0, -1], k = 3Output
    15 min read
  • Longest subarray having average greater than or equal to x | Set-2
    Given an array of N integers. The task is to find the longest contiguous subarray so that the average of its elements is greater than or equal to a given number X. Examples: Input: arr = {1, 1, 2, -1, -1, 1}, X = 1Output: 3Length of longest subarraywith average >= 1 is 3 i.e.((1+1+2)/3)= 1.333Inp
    11 min read
  • Longest subarray having sum of elements atmost K
    Given an array arr[] of size N and an integer K, the task is to find the length of the largest subarray having the sum of its elements at most K, where K > 0. Examples: Input: arr[] = {1, 2, 1, 0, 1, 1, 0}, k = 4Output: 5Explanation: {1, 2, 1} => sum = 4, length = 3 {1, 2, 1, 0}, {2, 1, 0, 1}
    12 min read
  • Longest Subarray with first element greater than or equal to Last
    Given an array of integers arr[] of size n. Your task is to find the maximum length subarray such that its first element is greater than or equals to the last element. Examples: Input : arr[] = [-5, -1, 7, 5, 1, -2]Output : 5Explanation : Subarray {-1, 7, 5, 1, -2} forms maximum length subarray with
    15+ min read
  • Longest subarray in which all elements are smaller than K
    Given an array arr[] consisting of N integers and an integer K, the task is to find the length of the longest subarray in which all the elements are smaller than K. Constraints:0 <= arr[i]  <= 10^5 Examples:  Input: arr[] = {1, 8, 3, 5, 2, 2, 1, 13}, K = 6Output: 5Explanation:There is one poss
    11 min read
  • Longest subarray in which all elements are a factor of K
    Given an array A[] of size N and a positive integer K, the task is to find the length of the longest subarray such that all elements of the subarray is a factor of K. Examples: Input: A[] = {2, 8, 3, 10, 6, 7, 4, 9}, K = 60Output: 3Explanation: The longest subarray in which all elements are a factor
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences