Count Subarrays Where Max Element Appears at Least K Times (LeetCode 2962): Solution and Explanation

Medium
Array
Sliding Window

Count the subarrays that contain the array's overall maximum value at least k times.

Intuition

The maximum M of the whole array is fixed before we start, so every other value is just filler. All that matters about a subarray is how many copies of M it holds.

Adding elements never removes copies. If nums[j..right] holds at least k copies, so does nums[j-1..right], nums[j-2..right] and so on. For a fixed right end, the valid starts are a prefix 0..L-1 of the array.

A sliding window finds that L. Grow the window to the right, and whenever it holds k copies, move the left edge forward until it holds only k - 1. Now left is the first start that fails, so exactly left starts succeed.

Both pointers only move forward, so the whole scan is linear.

Approach: Sliding window that counts valid starts

  1. Compute mx = max(nums). Set count = 0, left = 0, total = 0 (64-bit).
  2. For each right, add one to count if nums[right] == mx.
  3. While count >= k: if nums[left] == mx subtract one from count, then increment left.
  4. Add left to total: starts 0..left-1 all give a subarray ending at right with at least k copies.
  5. Return total.

Step-by-step example

nums = [1,3,2,3,3], k = 2
  1. mx = 3. right = 0 (1) and right = 1 (3): count reaches 1, below k, so left stays 0 and nothing is added.
  2. right = 2 (value 2): count is still 1. total stays 0.
  3. right = 3 (3): count = 2. Shrink: nums[0] = 1 is filler, left = 1; nums[1] = 3 is a copy, count = 1, left = 2. Add 2, total = 2.
  4. right = 4 (3): count = 2. Shrink: nums[2] = 2, left = 3; nums[3] = 3, count = 1, left = 4. Add 4, total = 6.
  5. The answer is 6.

Code: Python, Java, C++

1class Solution:
2    def countSubarrays(self, nums: List[int], k: int) -> int:
3        mx = max(nums)
4        total = 0
5        count = left = 0
6        for right, x in enumerate(nums):
7            if x == mx:
8                count += 1
9            while count >= k:
10                if nums[left] == mx:
11                    count -= 1
12                left += 1
13            total += left
14        return total
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

right visits each index once and left moves forward at most n times in total.

Space

O(1)

Only the maximum, two pointers, the copy count and the total are stored.

Other approaches

Positions of the maximum (time O(n), space O(n))

Record the indices where M appears. For a right end with at least k copies at or before it, the valid starts are 0..p where p is the k-th most recent position. Sum p + 1 over all right ends.

Count the complement (time O(n), space O(1))

Count subarrays with at most k - 1 copies using a sliding window, then subtract from n(n+1)/2. Same complexity, one extra subtraction.

Common mistakes

  • Using the maximum of the current window instead of the global maximum. The problem fixes M as the maximum of the whole array.
  • Adding right - left + 1 out of habit. Here the counted subarrays are the ones that start before the window, so the amount to add is left.
  • Using a 32-bit total. With n = 10^5 and every value equal the answer is about 5 * 10^9.
  • Stopping the shrink at count == k - 1 is right; shrinking further or not at all gives the wrong left.

Frequently asked questions

Why add left and not the window length?

After shrinking, the window [left, right] holds k - 1 copies, so it is not valid. Each start strictly before left adds back at least one copy and makes the subarray valid. There are exactly left such starts.

What if k is larger than the number of copies of the maximum?

count never reaches k, left stays 0, and the answer is 0. No special case is needed.

How is this different from Count Subarrays With Fixed Bounds?

Both count subarrays by their right end. Here the condition is monotone in the start (more elements never hurt), so a single left pointer suffices. Fixed Bounds also has values that break a subarray, which adds a wall position.