2527. Count Subarrays With Fixed Bounds
My accepted Python solution to LeetCode problem 2527, Count Subarrays With Fixed Bounds, running in 176ms.
- Difficulty: Hard
- Python
- Runtime 176ms
- Memory 28.8MB
- Updated
Read the problem on LeetCode View on GitHub
The problem statement is LeetCode’s and stays on their site. What follows is my accepted solution.
Python
Accepted on LeetCode — runtime 176ms, memory 28.8MB, accepted 2025-12-29.
class Solution:
def countSubarrays(self, nums: List[int], minK: int, maxK: int) -> int:
result = 0
min_pos = max_pos = bad_pos = -1
for i, num in enumerate(nums):
# If current element is out of bounds, reset
if num < minK or num > maxK:
bad_pos = i
# Update positions of minK and maxK
if num == minK:
min_pos = i
if num == maxK:
max_pos = i
# Count valid subarrays ending at position i
# The subarray must start after bad_pos and include both min_pos and max_pos
result += max(0, min(min_pos, max_pos) - bad_pos)
return result