Number of Subarrays with Bounded Maximum — LeetCode 795 Python Solution
- Problem
- #795
- Pattern
- Two Pointers
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Given an integer array nums and two integers left and right, return the number of contiguous non-empty subarrays such that the value of the maximum array element in that subarray is in the range [left, right]. The test cases are generated so that the answer will fit in a 32-bit integer.
Example
- Input
- nums = [2,1,4,3], left = 2, right = 3
- Output
- 3
- Explanation
- There are three subarrays that meet the requirements: [2], [2, 1], [3].
Python solution
class Solution:
def numSubarrayBoundedMax(self, nums: List[int], left: int, right: int) -> int:
def f(x):
cnt = t = 0
for v in nums:
t = 0 if v > x else t + 1
cnt += t
return cnt
return f(right) - f(left - 1)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) (after optional sort O(n log n)) |
| Space | O(1) auxiliary |
Pattern: Two Pointers
Use the order already in the input to discard half the search space at every step. LeetCode 795. Number of Subarrays with Bounded Maximum is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Two Pointers.
The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 795. Number of Subarrays with Bounded Maximum?
- LeetCode 795. Number of Subarrays with Bounded Maximum is rated Medium on LeetCode.
- What is the time complexity of LeetCode 795. Number of Subarrays with Bounded Maximum?
- The Python solution on this page runs in O(n) (after optional sort O(n log n)).
- What is the space complexity of LeetCode 795. Number of Subarrays with Bounded Maximum?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 795. Number of Subarrays with Bounded Maximum cover?
- LeetCode 795. Number of Subarrays with Bounded Maximum is tagged Array and Two Pointers on LeetCode.