882031. Longest Subarray with Majority Greater than K

Medium

Longest Subarray with Majority Greater than K

Slug: longest-subarray-with-majority-greater-than-k

Difficulty: Medium

Id: 882031

Topic Tags: prefix-sum, Hash

Company Tags: None

Summary

Given an array of integers and a number K, find the length of the longest subarray where the majority element is greater than K. The majority element is the element that appears more than half the size of the subarray.

Detailed Explanation

To solve this problem, we can use the prefix sum technique to keep track of the cumulative count of elements greater than K in each subarray. We maintain a hashmap to store the prefix sums and their corresponding indices.

Here's a step-by-step breakdown of the solution:

  1. Initialize a hashmap cumulative_sum to store the prefix sums and their indices.
  2. Iterate through the array, maintaining a running sum cumulative_sum.
  3. For each element in the array, calculate the cumulative sum by adding the current element to the previous cumulative sum.
  4. Check if the cumulative sum is greater than or equal to K. If it is, increment the count of majority elements.
  5. Update the hashmap with the current cumulative sum and its index.
  6. Initialize a variable max_length to store the length of the longest subarray.
  7. Iterate through the hashmap, updating max_length whenever we find a prefix sum that has more than half the size of the array.
  8. Return max_length.

Time complexity: O(n), where n is the size of the input array. Space complexity: O(n), for storing the cumulative sums and their indices in the hashmap.

Optimized Solutions

Java

View on GeeksforGeeks
import java.util.HashMap;
import java.util.Map;

public class Main {
    public static int longestSubarray(int[] arr, int K) {
        Map<Integer, Integer> cumulativeSum = new HashMap<>();
        int cumulativeSumCount = 0;
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] > K) {
                cumulativeSumCount++;
            } else {
                cumulativeSumCount -= 1;
            }
            cumulativeSum.put(cumulativeSumCount, i);
        }
        int maxLength = 0;
        for (int sum : cumulativeSum.keySet()) {
            if ((sum >= 0 && cumulativeSumCount - sum > K) || sum < 0) {
                maxLength = Math.max(maxLength, cumulativeSum.get(sum + K));
            }
        }
        return maxLength;
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5};
        int K = 3;
        System.out.println(longestSubarray(arr, K)); // Output: 3
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.