The Maximum Length of Semi-Decreasing Subarrays coding problem asks you to find the longest contiguous subarray where the first element is strictly greater than the last element — in other words, a subarray that "starts higher than it ends." This is called semi-decreasing because it only constrains the endpoints, not every pair of adjacent elements.
Google includes this problem to test candidates' understanding of monotonic stacks applied in a non-standard way. The brute-force O(n²) approach is trivial to state; the challenge lies in achieving O(n log n) or O(n) using a stack. Candidates who can identify that the relevant left endpoints form a decreasing stack, and the relevant right endpoints form an increasing stack, demonstrate strong algorithmic intuition.
The solution uses a monotonic stack approach.
nums[i] is greater than the current stack top's value (i.e., keep only indices whose values form a strictly decreasing sequence from left to right as potential left endpoints for maximum reach).stack.top() > nums[j] — each such pop gives a valid subarray from the popped index to j, updating the max length.This ensures each index is processed once: O(n) total.
Array: [3, 1, 4, 1, 5, 2]
For the Array Monotonic Stack Sorting Stack interview pattern, remember that "semi-decreasing" constraints (start > end) are a monotonic stack classic. Build the left stack as strictly decreasing-values, then sweep right-to-left as the right pointer. This two-pass technique appears in many "longest subarray with endpoint constraint" problems.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Finding the Number of Visible Mountains | Medium | Solve | |
| Car Fleet | Medium | Solve | |
| The Number of Weak Characters in the Game | Medium | Solve | |
| Max Chunks To Make Sorted | Medium | Solve | |
| Max Chunks To Make Sorted II | Hard | Solve |