Longest Strictly Increasing or Strictly Decreasing Subarray - Problem

Given an array of integers nums, you need to find the longest contiguous subarray that is either strictly increasing or strictly decreasing.

A subarray is strictly increasing if each element is greater than the previous one (no equal elements allowed). Similarly, a subarray is strictly decreasing if each element is smaller than the previous one.

Goal: Return the maximum length among all such subarrays.

Example: In array [1, 3, 2, 4], we have increasing subarray [1, 3] of length 2, and decreasing subarray [3, 2] of length 2. The answer is 2.

Input & Output

example_1.py โ€” Basic Increasing and Decreasing
$ Input: [1,3,2,4]
โ€บ Output: 2
๐Ÿ’ก Note: The array contains [1,3] (increasing, length 2) and [3,2] (decreasing, length 2). Both have length 2, so the answer is 2.
example_2.py โ€” Longer Increasing Sequence
$ Input: [1,2,3,4,5,3,2,1]
โ€บ Output: 5
๐Ÿ’ก Note: The longest subarray is [1,2,3,4,5] which is strictly increasing with length 5. There's also [5,3,2,1] (decreasing, length 4), but 5 is larger.
example_3.py โ€” Single Element
$ Input: [5]
โ€บ Output: 1
๐Ÿ’ก Note: A single element forms a subarray of length 1, which is considered both increasing and decreasing.

Constraints

  • 1 โ‰ค nums.length โ‰ค 105
  • -109 โ‰ค nums[i] โ‰ค 109
  • Note: Single element subarrays have length 1

Visualization

Tap to expand
๐Ÿ”๏ธ Mountain Trail Analysis132465๐Ÿ”บ Longest Uphill: 3 segmentsCurrent Tracking๐Ÿ”บ Uphill: 3๐Ÿ”ป Downhill: 1Max Length: 3LegendUphill movementDownhill movementBest segment
Understanding the Visualization
1
Start the Journey
Begin at the first elevation point with both uphill and downhill counters set to 1
2
Track Direction Changes
As you move, increment the appropriate counter based on elevation change
3
Reset on Direction Change
When switching from uphill to downhill (or vice versa), reset the opposite counter
4
Record Maximum
Keep track of the longest consistent segment you've encountered
Key Takeaway
๐ŸŽฏ Key Insight: Track both increasing and decreasing trends simultaneously in one pass, resetting counters when direction changes - this gives us O(n) optimal performance.
Asked in
Google 25 Amazon 18 Microsoft 15 Meta 12
28.5K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen