10. Longest Subarray With Majority Greater Than K
The problem can be found at the following link: 🔗 Question Link
🧩 Problem Description
Given an array arr[] of size n and an integer k, find the length of the longest subarray in which the count of elements greater than k is strictly more than the count of elements less than or equal to k.
📘 Examples
Example 1:
Input:
arr = [1, 2, 3, 4, 1], k = 2Output:
3Explanation:
Subarrays [2, 3, 4] or [3, 4, 1] both have 2 elements > 2 and 1 element ≤ 2.
Example 2:
Input:
Output:
Explanation:
Full array has 4 elements > 2 and 0 elements ≤ 2, so length = 4.
🔒 Constraints
$
1 ≤ n = arr.size() ≤ 10^6$$
0 ≤ k ≤ 10^6$$
0 ≤ arr[i] ≤ 10^6$
✅ My Approach
Prefix‐Sum + Hash Map
We transform each element into +1 if it’s > k, or −1 otherwise. Then the problem reduces to finding the longest subarray whose sum is positive.
Algorithm Steps:
Initialize a prefix‐sum
s = 0and an empty hash mapfirstIdxmapping each seen prefix‐sum to its earliest index.Iterate through the array with index
i:Update
s += (arr[i] > k ? 1 : -1).If
s > 0, the subarray[0…i]has positive sum; updateres = i + 1.Else if
(s - 1)exists infirstIdx, a subarray ending atistarting afterfirstIdx[s - 1]has positive sum; updateres = max(res, i - firstIdx[s - 1]).If
sis not yet infirstIdx, storefirstIdx[s] = i.
Return
res(the maximum length found).
🧮 Time and Auxiliary Space Complexity
Expected Time Complexity:
O(n), since we make a single pass and each hash operation is amortized O(1).Expected Auxiliary Space Complexity:
O(n), for storing up tondistinct prefix‐sums in the hash map.
🧠 Code (C++)
⚡ Alternative Approaches
📊 2️⃣ Monotonic Stack + Prefix Sum
Algorithm Steps:
Construct a prefix sum array
Pof lengthn+1, whereP[0] = 0, and for eachi,P[i+1] = P[i] + (arr[i] > k ? 1 : -1).Build a monotonically decreasing stack of indices where the corresponding
P[i]values are strictly decreasing.Traverse the array from the end (
i = n) to the beginning (i = 0):While the stack is not empty and
P[i] > P[stack.top()], pop from the stack and computeres = max(res, i - idx).
Return
res.
✅ Why This Approach?
Achieves O(n) time and O(n) space complexity.
Avoids the use of hash maps, which can be beneficial in environments where hash map performance is unpredictable.
📝 Complexity Analysis:
Time: O(n)
Space: O(n)
📊 3️⃣ Balanced BST (Ordered Map)
Algorithm Steps:
Initialize a balanced binary search tree (e.g.,
map<int, int>) to store the earliest occurrence of each prefix sum.Iterate through the array, updating the prefix sum
sby adding1ifarr[i] > k, else subtracting1.If
s > 0, updateres = i + 1.If
sis not already in the map, insert it with the current index.Check if
s - 1exists in the map; if so, updateres = max(res, i - map[s - 1]).Return
res.
✅ Why This Approach?
Provides O(n log n) worst-case time complexity due to the balanced BST operations.
Deterministic performance without relying on hash functions.
📝 Complexity Analysis:
Time: O(n log n)
Space: O(n)
🆚 Comparison of Approaches
Approach
⏱️ Time
🗂️ Space
✅ Pros
⚠️ Cons
Prefix Sum + Hash Map
🟢 O(n)
🟢 O(n)
Simple, fastest average case
Potential hash collisions
Monotonic Stack + Prefix Sum
🟢 O(n)
🟢 O(n)
No hash map needed
Slightly more complex logic
Balanced BST (Ordered Map)
🔸 O(n log n)
🟢 O(n)
Deterministic performance
Slower due to log n factor
✅ Best Choice?
Scenario
Recommended Approach
Large n (up to 10^6), fastest
🥇 Prefix Sum + Hash Map
Avoid hashing, still linear
🥈 Monotonic Stack + Prefix
Guarantee tree-based lookup
🥉 Balanced BST
🧑💻 Code (Java)
🐍 Code (Python)
🧠 Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: 📬 Any Questions?. Let’s make this learning journey more collaborative!
⭐ If you find this helpful, please give this repository a star! ⭐
📍Visitor Count
Last updated