Count Subarrays With Loose Bounds Problem
Description
LeetCode Problem 4089.
You are given an integer array nums and two integers minK and maxK.
A loose-bound subarray is a subarray in which every element is greater than or equal to minK and less than or equal to maxK.
Return the number of loose-bound subarrays in nums.
Example 1:
Input: nums = [1,4,7,3], minK = 1, maxK = 5
Output: 4
Explanation:
The loose-bound subarrays are [1], [4], [3], and [1, 4]. The minimum value in these subarrays is at least minK = 1 and the maximum value is at most maxK = 5.
Example 2:
Input: nums = [1,1], minK = 1, maxK = 1
Output: 3
Explanation:
The loose-bound subarrays are [1], [1], and [1, 1]. The minimum value in these subarrays is at least minK = 1 and the maximum value is at most maxK = 1.
Constraints:
2 <= nums.length <= 10^51 <= nums[i], minK, maxK <= 10^6
Solution
Approach: Two Pointers
A subarray is valid exactly when every element lies in [minK, maxK], so an out-of-range element splits the array and no valid subarray crosses it.
Let l be the start of the current stretch of in-range elements. For each right end r: if nums[r] is out of range, set l = r + 1; otherwise every subarray ending at r and starting in [l, r] is valid, so add r - l + 1.
Complexity: O(n) time and O(1) space. The count can exceed 32 bits, so use a 64-bit integer.
class Solution:
def countSubarrays(self, nums: List[int], minK: int, maxK: int) -> int:
ans = l = 0
for r, x in enumerate(nums):
if x < minK or x > maxK:
l = r + 1
else:
ans += r - l + 1
return ans