Count Subarrays With Fixed Bounds Problem
#2444
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2444.
You are given an integer array nums and two integers minK and maxK.
A fixed-bound subarray of nums is a subarray that satisfies the following conditions:
- The minimum value in the subarray is equal to
minK. - The maximum value in the subarray is equal to
maxK.
Return the number of fixed-bound subarrays.
A subarray is a contiguous part of an array.
Example 1:
Input: nums = [1,3,5,2,7,5], minK = 1, maxK = 5
Output: 2
Explanation: The fixed-bound subarrays are [1,3,5] and [1,3,5,2].
Example 2:
Input: nums = [1,1,1,1], minK = 1, maxK = 1
Output: 10
Explanation: Every subarray of nums is a fixed-bound subarray. There are 10 possible subarrays.
Constraints:
2 <= nums.length <= 10^51 <= nums[i], minK, maxK <= 10^6
Solution
Approach: Enumerate the Right Endpoint
A fixed-bound subarray has all its values in [minK, maxK], contains minK at least once and maxK at least once.
For every right endpoint i, count the valid left endpoints. We keep three indexes, all starting at -1:
- k: the last position holding a value outside [minK, maxK]. The left endpoint must be after k.
- j1: the last position holding minK.
- j2: the last position holding maxK. The left endpoint must be at or before min(j1, j2).
So the right endpoint i contributes max(0, min(j1, j2) - k) subarrays. Add these up.
Complexity: O(n) time and O(1) space.
class Solution:
def countSubarrays(self, nums: List[int], minK: int, maxK: int) -> int:
j1 = j2 = k = -1
ans = 0
for i, v in enumerate(nums):
if v < minK or v > maxK:
k = i
if v == minK:
j1 = i
if v == maxK:
j2 = i
ans += max(0, min(j1, j2) - k)
return ans