Count Strictly Increasing Subarrays Problem
#2393
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 2393.
You are given an array nums consisting of positive integers.
Return the number of subarrays of nums that are in strictly increasing order.
A subarray is a contiguous part of an array.
Example 1:
Input: nums = [1,3,5,4,4,6]
Output: 10
Explanation: The strictly increasing subarrays are the following:
- Subarrays of length 1: [1], [3], [5], [4], [4], [6].
- Subarrays of length 2: [1,3], [3,5], [4,6].
- Subarrays of length 3: [1,3,5].
The total number of subarrays is 6 + 3 + 1 = 10.
Example 2:
Input: nums = [1,2,3,4,5]
Output: 15
Explanation: Every subarray is strictly increasing. There are 15 possible subarrays that we can take.
Constraints:
1 <= nums.length <= 10^51 <= nums[i] <= 10^6
Solution
Approach: Enumeration
Count the strictly increasing subarrays that end at each position. Keep cnt, the length of the current strictly increasing run: it grows by one when the element is larger than the previous one and resets to 1 otherwise. Exactly cnt increasing subarrays end at the current element, so add cnt to the answer at each step.
Complexity: time O(n), space O(1), where n is the length of the array.
class Solution:
def countSubarrays(self, nums: List[int]) -> int:
ans = cnt = 1
for x, y in zip(nums, nums[1:]):
if x < y:
cnt += 1
else:
cnt = 1
ans += cnt
return ans