You are given an array of integers nums. Write a function to find the number of subarrays that are "strictly decreasing". Please write a function that solves this problem, and explain your algorithm.
Assistant
We need to solve: Given an array of integers nums, find the number of subarrays that are "strictly decreasing". A subarray is a contiguous part of the array. "Strictly decreasing" means each element is strictly less than the previous one: for subarray of length 1, is that considered strictly decreasing? Typically, decreasing means a1 > a2 > a3 ... For length 1, there is no pair, but sometimes it's considered trivially decreasing. However, we need to interpret from typical problems: "strictly decreasing subarray" often includes subarrays of length 1 as they are vacuously decreasing? Actually, let's think: A sequence of length 1 is both increasing and decreasing by some definitions, but "strictly decreasing" requires that for every i, a[i] > a[i+1]. For length 1, there is no i such that i+1 exists, so the condition holds vacuously. So it is decreasing. But some problems might count only subarrays of length >=2. Need to check typical definitions. In LeetCode problem "Number of Smooth Descent Periods of a Stock", they count single days as smooth descent periods (length 1). In other contexts like "Count number of strictly decreasing subarrays", it usually includes length 1. We'll need to decide. Usually such problems count all subarrays that are strictly decreasing, including length 1. But the phrase "subarrays that are strictly decreasing" might include length 1. However, to be safe, we could mention both and maybe count length 1 as well. I'll read the prompt: "You are given an array of integers nums. Write a function to find the number of subarrays that are 'strictly decreasing'." It doesn't specify excluding singletons. So we will assume that subarrays of length 1 are considered strictly decreasing. But we could clarify in explanation.
Goal: Write a function that takes array nums and returns count.
We need to design efficient algorithm: O(n) time.
Observation: A strictly decreasing subarray is a maximal contiguous segment where each next element is strictly less than previous. Any contiguous subarray within that segment is also strictly decreasing? Actually, if we have a maximal decreasing run, say from index i to j (inclusive) where for all k in [i, j-1], nums[k] > nums[k+1]. Then any contiguous subarray within that run is also strictly decreasing because the property is inherited. So for a run of length L (number of elements), the number of subarrays that are strictly decreasing within that run is L*(L+1)/2 (all possible contiguous subarrays of that run). However, careful: Not every subarray within a decreasing run is decreasing? Yes, any contiguous subarray of a strictly decreasing sequence is also strictly decreasing. Because if a1 > a2 > ... > aL, then any consecutive subsequence a_i, a_{i+1}, ... a_j satisfies a_k > a_{k+1} for each k in [i, j-1]. So it's strictly decreasing. So total count = sum over all maximal decreasing runs of L*(L+1)/2.
Thus algorithm: traverse array, compute lengths of maximal strictly decreasing runs. Initialize count=0, current run length=1 (since single element considered). For i from 1 to n-1: if nums[i-1] > nums[i] (strictly decreasing), then current run length++ else add run length*(run length+1)//2 to count, reset run length=1. After loop, add last run's count.
But also note: The prompt says "write a function that solves this problem, and explain your algorithm." So we need to provide the explanation and code.
We'll produce solution with code and comments.
Potential nuance: Some might treat only subarrays of length >=2. But we can mention and adjust. To be safe, maybe count length 1 as well? I'll assume length 1 included. However, we can easily modify by subtracting n (number of single-element subarrays) if needed. But let's follow typical interpretation: include length 1.
But also check: In many problems, they ask "strictly decreasing subarrays", and they often count subarrays of length 1. For example, LeetCode 978 "Longest Turbulent Subarray" includes length 1? That's different. I'll stick with length 1 included.
We'll produce final answer.
Now, let's structure: Explanation, then code.
Algorithm:
Initialize total = 0, length = 1.
Loop i from 1 to len(nums)-1:
if nums[i-1] > nums[i]: length += 1
else: total += length*(length+1)//2; length = 1
After loop, add total += length*(length+1)//2.
Return total.
Alternative: using a sliding approach counting contributions as we go: we could also add each element's contribution: for each position i, count the number of decreasing subarrays ending at i. For i=0, that's 1. For i>0, if nums[i-1] > nums[i], then dp[i] = dp[i-1] + 1; else dp[i]=1. Sum dp gives total. That's equivalent. We'll mention that as insight.
Time O(n), space O(1).
Edge Cases: empty array => 0.
Now produce final answer.
Solution Explanation
A subarray is a contiguous slice of the original array.
It is strictly decreasing if for every adjacent pair of elements we have
code
a[i] > a[i+1]
A subarray of length 1 satisfies this condition vacuously (there is no pair that can violate it), so we count those as well.
The key observation is that a maximal strictly decreasing segment (a run) of length L contains all possible strictly decreasing subarrays that lie completely inside it, because any contiguous slice of a strictly decreasing sequence is itself strictly decreasing.
The number of contiguous subarrays of a segment with L elements is the triangular number:
code
L * (L + 1) / 2
Therefore the total answer is the sum of those triangular numbers over all maximal decreasing runs in the array.
Algorithm (one‑pass)
If the input array is empty, return 0.
Initialise total = 0 – final count run_len = 1 – length of the current decreasing run (the first element starts a run of length 1).
Iterate i from 1 to n‑1:
If nums[i‑1] > nums[i] (still decreasing), increase run_len by 1.
Otherwise the run ends at i‑1. Add the contribution of the finished run: total += run_len * (run_len + 1) // 2
Reset run_len = 1 (start a new run at i).
After the loop, add the contribution of the last run: total += run_len * (run_len + 1) // 2.
Return total.
Correctness Proof
We prove that the algorithm returns the exact number of strictly decreasing subarrays.
Lemma 1
Any contiguous subarray of a strictly decreasing segment is itself strictly decreasing.
Proof. Let the segment be a[p], a[p+1], …, a[q] with a[k] > a[k+1] for all k ∈ [p, q-1].
Take any subarray a[i], a[i+1], …, a[j] where p ≤ i ≤ j ≤ q.
For any k with i ≤ k < j we have p ≤ k < q, so a[k] > a[k+1]. Hence the subarray is strictly decreasing. ∎
Lemma 2
For a maximal strictly decreasing run of length L, the number of strictly decreasing subarrays that lie completely inside this run equals L·(L+1)/2.
Proof. By Lemma 1 every contiguous subarray of the run is strictly decreasing, and there are exactly L·(L+1)/2 contiguous subarrays of an L‑element array (choose start and end indices). ∎
Lemma 3
During the scan, each maximal decreasing run is identified exactly once, and its length L is stored in run_len right before it is added to total.
Proof. The loop increases run_len as long as the decreasing condition holds. When the condition fails at index i, the run that ended at i‑1 has length run_len. The algorithm then adds its contribution and resets run_len to 1, starting a new run at i. If the condition never fails after the last element, the final run is added after the loop. Thus each maximal run contributes exactly once. ∎
Theorem
The algorithm returns the total number of strictly decreasing subarrays of nums.
Proof. By Lemma 3, the algorithm partitions the array into disjoint maximal decreasing runs and adds, for each run of length L, the term L·(L+1)/2. By Lemma 2 this term equals the number of strictly decreasing subarrays that lie inside that run. Since any strictly decreasing subarray must be wholly contained in exactly one maximal run (otherwise it would break the decreasing property at a boundary), the sum over all runs counts every strictly decreasing subarray exactly once. Therefore total equals the desired count. ∎
Complexity Analysis
The array is traversed once. Time: O(n), where n = len(nums). Space: O(1) – only a few integer variables.
Reference Implementation (Python 3)
python
def count_strictly_decreasing_subarrays(nums):
"""
Returns the number of strictly decreasing subarrays in the given list of integers.
Subarrays of length 1 are counted as strictly decreasing.
"""
if not nums:
return 0
total = 0 # accumulator for the answer
run_len = 1 # length of the current decreasing run
for i in range(1, len(nums)):
if nums[i - 1] > nums[i]:
run_len += 1
else:
total += run_len * (run_len + 1) // 2
run_len = 1
total += run_len * (run_len + 1) // 2 # add the last run
return total
Example usage
python
print(count_strictly_decreasing_subarrays([6, 5, 4, 3, 2])) # 15 (5·6/2)
print(count_strictly_decreasing_subarrays([5, 1, 2, 3, 0])) # 7
# Explanation for second example:
# runs: [5] (len=1) → 1, [1,2,3] is increasing → each single → 3 → total so far 4,
# run [0] (len=1) → +1, plus the decreasing pair [3,0] (part of run length 2? Actually check:
# The array: index0=5, index1=1 (5>1) -> run_len=2? Wait: 5>1, so run_len becomes 2? Let's simulate:
# i=1: nums[0]>nums[1] (5>1) -> run_len=2.
# i=2: nums[1]>nums[2]? 1>2 false -> add 2*3/2=3, reset run_len=1.
# i=3: 2>3 false -> add 1*2/2=1 (single 2), reset run_len=1.
# i=4: 3>0 true -> run_len=2, loop ends, add 2*3/2=3. Total = 3+1+3=7.
# Subarrays: [5],[1],[2],[3],[0],[5,1],[3,0] -> 7.
The function satisfies the required O(n) time and O(1) space constraints.