Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
You are given an integer array nums and a positive integer k.
Return the number of subarrays where the maximum element of nums appears at least k times in that subarray.
A subarray is a contiguous sequence of elements within an array.
Example 1:
Input: nums = [1,3,2,3,3], k = 2 Output: 6 Explanation: The subarrays that contain the element 3 at least 2 times are: [1,3,2,3], [1,3,2,3,3], [3,2,3], [3,2,3,3], [2,3,3] and [3,3].
Example 2:
Input: nums = [1,4,2,1], k = 3 Output: 0 Explanation: No subarray contains the element 4 at least 3 times.
Constraints:
1 <= nums.length <= 1051 <= nums[i] <= 1061 <= k <= 105Problem summary: You are given an integer array nums and a positive integer k. Return the number of subarrays where the maximum element of nums appears at least k times in that subarray. A subarray is a contiguous sequence of elements within an array.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Sliding Window
[1,3,2,3,3] 2
[1,4,2,1] 3
find-the-number-of-subarrays-where-boundary-elements-are-maximum)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2962: Count Subarrays Where Max Element Appears at Least K Times
class Solution {
public long countSubarrays(int[] nums, int k) {
int mx = Arrays.stream(nums).max().getAsInt();
int n = nums.length;
long ans = 0;
int cnt = 0, j = 0;
for (int x : nums) {
while (j < n && cnt < k) {
cnt += nums[j++] == mx ? 1 : 0;
}
if (cnt < k) {
break;
}
ans += n - j + 1;
cnt -= x == mx ? 1 : 0;
}
return ans;
}
}
// Accepted solution for LeetCode #2962: Count Subarrays Where Max Element Appears at Least K Times
func countSubarrays(nums []int, k int) (ans int64) {
mx := slices.Max(nums)
n := len(nums)
cnt, j := 0, 0
for _, x := range nums {
for ; j < n && cnt < k; j++ {
if nums[j] == mx {
cnt++
}
}
if cnt < k {
break
}
ans += int64(n - j + 1)
if x == mx {
cnt--
}
}
return
}
# Accepted solution for LeetCode #2962: Count Subarrays Where Max Element Appears at Least K Times
class Solution:
def countSubarrays(self, nums: List[int], k: int) -> int:
mx = max(nums)
n = len(nums)
ans = cnt = j = 0
for x in nums:
while j < n and cnt < k:
cnt += nums[j] == mx
j += 1
if cnt < k:
break
ans += n - j + 1
cnt -= x == mx
return ans
// Accepted solution for LeetCode #2962: Count Subarrays Where Max Element Appears at Least K Times
/**
* [2962] Count Subarrays Where Max Element Appears at Least K Times
*/
pub struct Solution {}
// submission codes start here
impl Solution {
pub fn count_subarrays(nums: Vec<i32>, k: i32) -> i64 {
let max = *nums.iter().max().unwrap();
let n = nums.len();
let mut result = 0;
let mut count = 0;
let mut left = 0;
for right in 0..n {
count += if nums[right] == max { 1 } else { 0 };
if count >= k {
result += (n - right) as i64;
}
while left <= right && count >= k {
count -= if nums[left] == max { 1 } else { 0 };
if count >= k {
result += (n - right) as i64;
}
left += 1;
}
}
result
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_2962() {
assert_eq!(6, Solution::count_subarrays(vec![1, 3, 2, 3, 3], 2));
assert_eq!(0, Solution::count_subarrays(vec![1, 4, 2, 1], 3));
}
}
// Accepted solution for LeetCode #2962: Count Subarrays Where Max Element Appears at Least K Times
function countSubarrays(nums: number[], k: number): number {
const mx = Math.max(...nums);
const n = nums.length;
let [cnt, j] = [0, 0];
let ans = 0;
for (const x of nums) {
for (; j < n && cnt < k; ++j) {
cnt += nums[j] === mx ? 1 : 0;
}
if (cnt < k) {
break;
}
ans += n - j + 1;
cnt -= x === mx ? 1 : 0;
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
For each starting index, scan the next k elements to compute the window aggregate. There are n−k+1 starting positions, each requiring O(k) work, giving O(n × k) total. No extra space since we recompute from scratch each time.
The window expands and contracts as we scan left to right. Each element enters the window at most once and leaves at most once, giving 2n total operations = O(n). Space depends on what we track inside the window (a hash map of at most k distinct elements, or O(1) for a fixed-size window).
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Using `if` instead of `while` leaves the window invalid for multiple iterations.
Usually fails on: Over-limit windows stay invalid and produce wrong lengths/counts.
Fix: Shrink in a `while` loop until the invariant is valid again.