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 = 2
Output:
3
Explanation:
Subarrays [2, 3, 4]
or [3, 4, 1]
both have 2 elements > 2 and 1 element โค 2.
Example 2:
Input:
arr = [6, 5, 3, 4], k = 2
Output:
4
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 = 0
and an empty hash mapfirstIdx
mapping 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 ati
starting afterfirstIdx[s - 1]
has positive sum; updateres = max(res, i - firstIdx[s - 1])
.If
s
is 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 ton
distinct prefixโsums in the hash map.
๐ง Code (C++)
class Solution {
public:
int longestSubarray(vector<int>& arr, int k) {
unordered_map<int,int> firstIdx;
int s = 0, res = 0;
for (int i = 0; i < arr.size(); ++i) {
s += (arr[i] > k ? 1 : -1);
if (s > 0) {
res = i + 1;
} else {
if (!firstIdx.count(s)) firstIdx[s] = i;
if (firstIdx.count(s - 1))
res = max(res, i - firstIdx[s - 1]);
}
}
return res;
}
};
๐งโ๐ป Code (Java)
class Solution {
public int longestSubarray(int[] arr, int k) {
Map<Integer,Integer> firstIdx = new HashMap<>();
int s = 0, res = 0;
for (int i = 0; i < arr.length; i++) {
s += arr[i] > k ? 1 : -1;
if (s > 0) {
res = i + 1;
} else {
firstIdx.putIfAbsent(s, i);
if (firstIdx.containsKey(s - 1)) {
res = Math.max(res, i - firstIdx.get(s - 1));
}
}
}
return res;
}
}
๐ Code (Python)
class Solution:
def longestSubarray(self, arr, k):
first_idx = {}
s = res = 0
for i, val in enumerate(arr):
s += 1 if val > k else -1
if s > 0:
res = i + 1
else:
first_idx.setdefault(s, i)
if (s - 1) in first_idx:
res = max(res, i - first_idx[s - 1])
return res
๐ง 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