MediumNo. 2962
Count Subarrays Where Max Element Appears at Least K Times — LeetCode 2962 Python Solution
- Pattern
- Sliding Window
- Topics
- Array, Sliding Window
- Reading time
- 3 min
- Source
- leetcode.com
The 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.
Example
- 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].
Python solution
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 ansComplexity
- Time
- O(n)where n is the length of the array nums
- Space · auxiliary
- O(1)
Pattern: Sliding Window
Collapse a nested loop over every subarray into a single pass with two indices. LeetCode 2962. Count Subarrays Where Max Element Appears at Least K Times is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Sliding Window.
The sliding window guide has the Python template for the pattern and the 116 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0239 | Sliding Window Maximum | Hard |
| 0643 | Maximum Average Subarray I | Easy |
| 1052 | Grumpy Bookstore Owner | Medium |
| 1343 | Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold | Medium |
| 1438 | Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit | Medium |
| 1499 | Max Value of Equation | Hard |
Frequently asked questions
- How hard is LeetCode 2962. Count Subarrays Where Max Element Appears at Least K Times?
LeetCode 2962. Count Subarrays Where Max Element Appears at Least K Times is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2962. Count Subarrays Where Max Element Appears at Least K Times?
The Python solution on this page runs in O(n), where n is the length of the array nums.
- What is the space complexity of LeetCode 2962. Count Subarrays Where Max Element Appears at Least K Times?
The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 2962. Count Subarrays Where Max Element Appears at Least K Times cover?
LeetCode 2962. Count Subarrays Where Max Element Appears at Least K Times is tagged Array and Sliding Window on LeetCode.