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

You're given an integer array nums and a positive integer k. Your task is to count how many subarrays contain the maximum element of the entire array at least k times.

A subarray is a contiguous sequence of elements within the array. For example, in array [3, 1, 5, 1, 5], the maximum element is 5, and you need to find all subarrays where 5 appears at least k times.

Key Points:

  • First identify the maximum element in the entire array
  • Then count subarrays where this max element appears โ‰ฅ k times
  • Consider all possible contiguous subsequences

This problem tests your understanding of subarrays and efficient counting techniques using sliding window approaches.

Input & Output

example_1.py โ€” 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], [1,3,2,3,3]. Total = 6 subarrays.
example_2.py โ€” Single Max Element
$ Input: nums = [1,4,2,1], k = 3
โ€บ Output: 0
๐Ÿ’ก Note: Max element is 4, which appears only once. No subarray can have 4 appearing at least 3 times, so result is 0.
example_3.py โ€” All Same Elements
$ Input: nums = [5,5,5], k = 2
โ€บ Output: 3
๐Ÿ’ก Note: Max element is 5 (appears 3 times). Subarrays with at least 2 occurrences: [5,5], [5,5], [5,5,5]. Total = 3 subarrays.

Constraints

  • 1 โ‰ค nums.length โ‰ค 105
  • 1 โ‰ค nums[i] โ‰ค 106
  • 1 โ‰ค k โ‰ค nums.length
  • The array always contains at least one element

Visualization

Tap to expand
๐ŸŽซ Concert VIP Section ScannerVenue Layout: [Regular, Regular, VIP, Regular, VIP] | Need k=2 VIPs per sectionRegularRegularVIPRegularVIP๐Ÿ” Smart Scanning Process:Step 1: Scanner reaches position 2 (first VIP) โ†’ VIP positions: [2]Step 2: Scanner reaches position 4 (second VIP) โ†’ VIP positions: [2, 4] โœ…Step 3: Now we have k=2 VIPs! Count valid sections ending at position 4:โ€ข Sections can start at positions 0, 1, or 2 (before/at first VIP position)๐ŸŽฏ Result: 3 valid sections found in O(1) time at this position!Total algorithm complexity: O(n) instead of O(nยณ)
Understanding the Visualization
1
Identify VIPs
First pass identifies who the VIP guests are (maximum element value)
2
Track Positions
As you scan, keep track of where VIP guests are located
3
Smart Counting
When you have k VIPs in view, count all valid sections ending at current position
4
Efficient Result
Each position processed in O(1) time, total O(n) complexity
Key Takeaway
๐ŸŽฏ Key Insight: Instead of checking every section individually (slow), track VIP positions and count valid sections mathematically (fast)!
Asked in
Google 45 Meta 38 Amazon 32 Microsoft 28
73.8K Views
High Frequency
~25 min Avg. Time
1.8K 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