
Problem Statement
In this task, you are provided with an array of integers called nums
. Your goal is to find and return the number of contiguous subarrays where the first element, or the leftmost element, of the subarray is the smallest or not larger than any other elements within that subarray. The concept of subarrays is central to this problem. A subarray is defined as a sequence of elements that occur in order consecutively in the original array.
Examples
Example 1
Input:
nums = [1,4,2,5,3]
Output:
11
Explanation:
There are 11 valid subarrays: [1],[4],[2],[5],[3],[1,4],[2,5],[1,4,2],[2,5,3],[1,4,2,5],[1,4,2,5,3].
Example 2
Input:
nums = [3,2,1]
Output:
3
Explanation:
The 3 valid subarrays are: [3],[2],[1].
Example 3
Input:
nums = [2,2,2]
Output:
6
Explanation:
There are 6 valid subarrays: [2],[2],[2],[2,2],[2,2],[2,2,2].
Constraints
1 <= nums.length <= 5 * 104
0 <= nums[i] <= 105
Approach and Intuition
Understand that for any given element in the
nums
array, if it serves as the leftmost element in a subarray and is the smallest within that subarray, then all conceivable subarrays starting from this position must be valid up until the first element that is smaller than this starting element is encountered or the end of the array is reached.Given this observation, approach the solution by iterating through each element in the
nums
array, using it as the potential start of a new subarray.For each starting element, traverse the array to the right as long as each subsequent element does not exceed the starting element. Count all such possible subarrays which can be formed with the starting element as the smallest.
Accumulate the counts from each valid subarray starting point to get the total number of valid subarrays across the entire array.
Considering the Examples:
In the first example, the array
[1,4,2,5,3]
leads to11
valid subarrays. Starting from each index and expanding outward until the condition breaks, helps in understanding how these valid subarrays are formed:- Starting with
1
, the subarray can expand until it includes the entire array since all elements are either equal or larger. - Starting with
4
, only single-element subarrays are valid because every subsequent number is either smaller or the subarray has already been counted in the previous steps. - Continue this for each element to calculate the total number of valid subarrays.
- Starting with
- This approach leverages the sequential nature of subarrays and the ordered checking based on conditions specified (leftmost not larger than others). This solution ensures that each potential subarray is evaluated efficiently according to the conditions.
Solutions
- C++
class Solution {
public:
int countValidSubarrays(vector<int>& elements) {
int total = 0;
stack<int> indices;
for (int index = 0; index < elements.size(); index++) {
while (!indices.empty() && elements[index] < elements[indices.top()]) {
total += (index - indices.top());
indices.pop();
}
indices.push(index);
}
while (!indices.empty()) {
total += (elements.size() - indices.top());
indices.pop();
}
return total;
}
};
The provided C++ code aims to solve the problem of counting valid subarrays within a given vector of integers. The technique used involves a stack to store indices of array elements under certain conditions, leveraging the Monotonic Stack method that helps in maintaining element order for quick comparison and validity checks.
To clarify the approach:
- Initialize a counter
total
to zero which will store the result, i.e., the total number of valid subarrays. - Create a
stack<int>
namedindices
that will maintain the indices of array elements that fulfill a condition during iteration. - Loop over the elements of the input vector:
- Within the loop, use a while loop to pop elements from the stack while the current element is smaller than the element at the top index of the stack. For each element popped, update
total
by adding the difference between the current index and the popped index. - Push the current index onto the stack afterwards.
- Within the loop, use a while loop to pop elements from the stack while the current element is smaller than the element at the top index of the stack. For each element popped, update
- After completing the primary loop, any remaining indices in the stack are processed in a final while loop. For each of these, add to
total
the difference between the size of the vector and the index at the top of the stack, then pop the stack. - Return the computed
total
as the solution.
This solution effectively counts and returns the total number of subarrays that meet a specific ordering criterion, doing so efficiently with the use of a stack to manage and compare indices dynamically.
- Java
class Solution {
public int countValidSubarrays(int[] elements) {
int count = 0;
Stack<Integer> indexStack = new Stack<>();
for (int index = 0; index < elements.length; index++) {
while(!indexStack.isEmpty() && elements[index] < elements[indexStack.peek()]) {
count += (index - indexStack.peek());
indexStack.pop();
}
indexStack.push(index);
}
while (!indexStack.isEmpty()) {
count += (elements.length - indexStack.peek());
indexStack.pop();
}
return count;
}
}
The provided Java solution efficiently counts the number of valid subarrays in a given integer array. Here’s a breakdown of how the program tackles this task:
Initialize a counter variable,
count
, to zero to store the total count of valid subarrays.Use a
Stack<Integer>
calledindexStack
to store indices of array elements. This stack helps keep track of the indices while iterating over the array to find valid subarrays.Loop through each element in the
elements
array using a for-loop:- Inside the loop, use a while-loop to check the conditions that determine if a subarray is valid:
- If
indexStack
is not empty and the current element (elements[index]
) is less than the element at the index stored at the top of the stack (elements[indexStack.peek()]
), then calculate and add the difference between the current index and the index popped from the stack tocount
.
- If
- Push the current index to
indexStack
.
- Inside the loop, use a while-loop to check the conditions that determine if a subarray is valid:
After looping through all elements, proceed to empty
indexStack
if it still contains any indices:- While
indexStack
is not empty, pop the top index and add the difference between the length of the array and the popped index tocount
.
- While
The final output, returned by int countValidSubarrays(int[] elements)
, is the total count of valid subarrays that meet the criteria where all sub-arrays (elements[i], elements[i+1], ..., elements[j])
should satisfy the condition that elements[i]
is less than or equal to all other elements in the sub-array.
No comments yet.