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 - Max Element Appears K Times INPUT nums array: 1 i=0 3 i=1 2 i=2 3 i=3 3 i=4 = max element (3) nums = [1, 3, 2, 3, 3] k = 2 Maximum element: 3 Appears 3 times total Need at least k=2 in subarray ALGORITHM STEPS 1 Find Maximum max(nums) = 3 2 Sliding Window Track count of max in window 3 Expand Right Until count of max >= k 4 Count Valid Add (n - right + 1) subarrays Valid Subarrays (6 total): [1,3,2,3] indices 0-3 [1,3,2,3,3] indices 0-4 [3,2,3] indices 1-3 [3,2,3,3] indices 1-4 [2,3,3] indices 2-4 [3,3] indices 3-4 Each has at least 2 occurrences of 3 FINAL RESULT Output: 6 OK - 6 valid subarrays Counting Breakdown: left=0: found at right=3 add 5-3=2 subarrays left=1: found at right=3 add 5-3=2 subarrays left=2: found at right=4 add 5-4=1 subarray left=3: found at right=4 add 5-4=1 subarray Key Insight: Use sliding window with two pointers. For each left position, find the smallest right where max appears k times. All subarrays extending beyond this right position are valid. Add (n - right) to count for each valid left. Time Complexity: O(n) | Space Complexity: O(1) - Each element visited at most twice. TutorialsPoint - Count Subarrays Where Max Element Appears at Least K Times | Optimal Solution
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