Count Subarrays Where Max Element Appears at Least K Times - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,3,2,3,3], k = 2
Output: 6
💡 Note: Max element is 3. Subarrays with at least 2 occurrences of 3: [3,2,3], [3,2,3,3], [2,3,3], [3,3], [3,2,3,3] (starting from index 1), and [3,3] (starting from index 3). Total: 6 subarrays.
Example 2 — Minimum Size
$ Input: nums = [1,4,2,1], k = 3
Output: 0
💡 Note: Max element is 4, appears only once. Since k=3 but max element appears only 1 time, no subarray can have the max element appearing at least 3 times.
Example 3 — All Same Elements
$ Input: nums = [3,3,3], k = 2
Output: 3
💡 Note: Max element is 3. Valid subarrays: [3,3] (indices 0-1), [3,3,3] (indices 0-2), and [3,3] (indices 1-2). Total: 3 subarrays.

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 106
  • 1 ≤ k ≤ nums.length

Visualization

Tap to expand
Count Subarrays: nums=[1,3,2,3,3], k=21323301234Maximum element = 3 (appears at indices 1, 3, 4)Valid subarrays (≥ 2 occurrences of 3):[3,2,3], [3,2,3,3], [2,3,3], [3,3], [3,2,3,3], [3,3]Output: 6 subarrays
Understanding the Visualization
1
Input
Array nums=[1,3,2,3,3] and k=2
2
Find Max
Maximum element is 3
3
Count Valid
Find subarrays with at least 2 occurrences of 3
Key Takeaway
🎯 Key Insight: Use sliding window to efficiently track when max element count reaches k
Asked in
Google 25 Amazon 18 Microsoft 15
28.5K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen