You are given an array of integers nums. Write a function to find the number of subarrays that are sorted in ascending order. Please write a function that solves this problem, and explain your algorithm.
Assistant
We are given an array of integers nums. We need to find the number of subarrays that are sorted in ascending order.
A subarray is a contiguous part of the array. So we want to count all contiguous subarrays that are non-decreasing (ascending order, typically means non-strict? The problem says "sorted in ascending order", which usually means each element is less than or equal to the next? Actually, in many contexts, "ascending order" means non-decreasing. But sometimes it means strictly increasing? Let's check: Typically, when we say sorted in ascending order, we mean that for a subarray, we have a[i] <= a[i+1] for all i. However, the problem statement says "sorted in ascending order", and in programming contexts, it usually means non-decreasing. But let's see: if we have repeated numbers, is [1,1] considered sorted in ascending order? Yes, because it's non-decreasing. So we'll assume non-decreasing.
We want to count all subarrays that satisfy this property.
Approach:
One way is to iterate over all subarrays and check if they are sorted. But that would be O(n^2) time, which is acceptable for small n? But we can do better.
We can traverse the array and keep track of the length of the current non-decreasing sequence. For each index i, we can extend the current non-decreasing run. Then, the number of subarrays ending at i that are sorted is exactly the length of the current run (because any subarray that ends at i and is sorted must start at some index from the beginning of the run to i). Then we can sum these up.
Specifically:
Let count be the total number of sorted subarrays.
Let current_length be the length of the current non-decreasing run ending at the current index.
Initialize: current_length = 1, count = 1 (for the first element).
Then for i from 1 to n-1:
if nums[i] >= nums[i-1]:
current_length += 1
else:
current_length = 1
Then add current_length to count.
Why does this work?
Consider a non-decreasing run from index L to R (inclusive). The subarrays that end at R and are entirely within this run are: [L..R], [L+1..R], ..., [R..R]. There are exactly (R-L+1) such subarrays. And when we are at index i, if the run length is current_length, that means the run starts at i-current_length+1 and ends at i. So the number of sorted subarrays ending at i is current_length. And we accumulate.
But note: all subarrays of [1,2,3] are sorted, and there are 6.
Example: nums = [1,3,2]
i=0: current_length=1, count=1
i=1: 3>=1 -> current_length=2, count=3
i=2: 2<3 -> current_length=1, count=4
So we get 4. Let's list:
[1], [1,3], [3], [2] -> indeed 4.
However, what about [1,2]? That is not because 2 is after 3? Actually, [1,3,2] has subarrays:
[1] -> sorted
[1,3] -> sorted
[1,3,2] -> not
[3] -> sorted
[3,2] -> not
[2] -> sorted
So indeed 4.
So the algorithm is O(n) time and O(1) space.
Edge cases: empty array? If empty, return 0.
Implementation:
Steps:
if nums is empty: return 0
count = 0
current_length = 0
for i in range(len(nums)):
if i==0 or nums[i] >= nums[i-1]:
current_length += 1
else:
current_length = 1
count += current_length
return count
But wait: for i=0, we set current_length=1 and then add. Alternatively, we can start with current_length=0 and then for each i, if condition holds then increment else reset to 1, but for i=0 we want to set to 1. So we can do:
current_length = 0
for i in range(len(nums)):
if i == 0 or nums[i] >= nums[i-1]:
current_length += 1
else:
current_length = 1
count += current_length
But for i=0, the condition i==0 is true, so we do current_length += 1, but current_length starts at 0, so becomes 1. That works.
Alternatively, we can set current_length=1 at the beginning and start loop from i=1, but then we have to add the first element separately.
Let's code accordingly.
However, note: the problem says "ascending order". What if the array is strictly increasing? Then it's the same. What if there are duplicates? We use >= so duplicates are allowed.
But what if the array is decreasing? Then every element is a separate subarray.
Example: [5,4,3,2,1]
Each step: current_length=1 for each, so count = 5. Only single element subarrays.
Example: [1,2,1,2]
i0: cl=1, count=1
i1: 2>=1 -> cl=2, count=3
i2: 1<2 -> cl=1, count=4
i3: 2>=1 -> cl=2, count=6
List:
[1], [1,2], [2], [1], [1,2], [2] -> wait, are there 6? Let's list all subarrays:
[1] -> sorted
[1,2] -> sorted
[1,2,1] -> not
[1,2,1,2] -> not
[2] -> sorted
[2,1] -> not
[2,1,2] -> not
[1] -> sorted
[1,2] -> sorted
[2] -> sorted
So indeed: [1], [1,2], [2], [1], [1,2], [2] -> 6.
So it's correct.
Now, we write the function.
But note: the problem says "subarrays", which are contiguous.
Let's code:
def count_sorted_subarrays(nums):
if not nums:
return 0
count = 0
current_length = 0
for i in range(len(nums)):
if i == 0 or nums[i] >= nums[i-1]:
current_length += 1
else:
current_length = 1
count += current_length
return count
However, we must be cautious: the condition for the first element is handled by i==0. Alternatively, we can start with current_length=1 and then loop from i=1, but then we have to add the first element's contribution separately.
Another way:
def count_sorted_subarrays(nums):
n = len(nums)
if n == 0:
return 0
count = 1 # for the first element
current = 1
for i in range(1, n):
if nums[i] >= nums[i-1]:
current += 1
else:
current = 1
count += current
return count
This is equivalent.
Let's choose the second for clarity.
Now, we must consider: what if the array is very long? The count might be large, but we return an integer.
Time complexity: O(n), space O(1).
Explanation: We traverse the array once. For each element, we determine the length of the longest non-decreasing subarray ending at that element. The number of sorted subarrays ending at that element is exactly that length. We accumulate.
Why is that? Because if we have a non-decreasing run from index j to i, then every subarray that ends at i and starts at any index from j to i is sorted. And there are exactly (i-j+1) such subarrays, which is the current length.
Therefore, by summing these, we count every sorted subarray exactly once (by its ending index).
So the algorithm is complete.
Let's write the function accordingly.
To solve this problem, we need to count all contiguous subarrays of a given array that are sorted in non-decreasing order. The key insight is recognizing that for any position i in the array, the number of sorted subarrays ending at i equals the length of the longest non-decreasing subarray ending at i. By traversing the array once and maintaining this length, we can efficiently accumulate the total count.
Approach
Initialization: Start with the first element. The subarray consisting of just the first element is trivially sorted, so initialize current_length = 1 and total_count = 1.
Traverse the array: For each subsequent element nums[i] (from index 1 to end):
If nums[i] >= nums[i-1], the current non-decreasing run continues, so increment current_length.
Otherwise, reset current_length to 1 (the subarray containing only nums[i]).
Add current_length to total_count because there are exactly current_length sorted subarrays ending at i (each starting from the beginning of the current run to i).
Return the total count: After processing all elements, total_count holds the number of all sorted subarrays.
Solution Code
python
def count_sorted_subarrays(nums):
if not nums:
return 0
total_count = 1
current_length = 1
for i in range(1, len(nums)):
if nums[i] >= nums[i-1]:
current_length += 1
else:
current_length = 1
total_count += current_length
return total_count
Explanation
Initialization: Handle the edge case of an empty array. For a non-empty array, start with the first element contributing 1 to the count.
Traversal: For each element, check if it continues the non-decreasing trend from the previous element:
Continuing trend: Extend the current run length. The number of new sorted subarrays ending at this position is exactly the new current_length (e.g., if run length becomes 3, new subarrays are [nums[i-2], nums[i-1], nums[i]], [nums[i-1], nums[i]], and [nums[i]]).
Breaking trend: Reset run length to 1 (only the element itself forms a sorted subarray ending here).
Accumulation: Each step adds the current run length to the total, ensuring every sorted subarray is counted exactly once (by its ending index).
Complexity
Time Complexity: O(n), where n is the length of nums. We traverse the array once.
Space Complexity: O(1), using only a few extra variables.
This approach efficiently counts all sorted subarrays by leveraging the contiguous property and the observation about run lengths.