Open In App

Longest Subarray having Majority Elements Greater Than K

Last Updated : 28 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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:
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(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

Similar Reads