Longest Strictly Increasing or Strictly Decreasing Subarray - Problem

You are given an array of integers nums. Return the length of the longest subarray of nums which is either strictly increasing or strictly decreasing.

A subarray is a contiguous non-empty sequence of elements within an array.

A strictly increasing subarray means each element is larger than the previous one.

A strictly decreasing subarray means each element is smaller than the previous one.

Input & Output

Example 1 — Mixed Pattern
$ Input: nums = [1,4,3,3,2]
Output: 2
💡 Note: The longest valid subarrays are [1,4] (strictly increasing) and [4,3] or [3,2] (strictly decreasing), all with length 2
Example 2 — Longer Increasing
$ Input: nums = [3,3,3,3]
Output: 1
💡 Note: All elements are equal, so no strictly increasing or decreasing subarray exists longer than 1
Example 3 — Perfect Sequence
$ Input: nums = [3,1,5,6,9]
Output: 4
💡 Note: The subarray [1,5,6,9] is strictly increasing with length 4

Constraints

  • 1 ≤ nums.length ≤ 1000
  • -109 ≤ nums[i] ≤ 109

Visualization

Tap to expand
Longest Increasing or Decreasing Subarray INPUT nums = [1, 4, 3, 3, 2] 1 i=0 4 i=1 3 i=2 3 i=3 2 i=4 Trend Analysis: 1 4 INC (len=2) 4 3 DEC (len=2) 3 = 3 RESET ALGORITHM STEPS 1 Initialize inc=1, dec=1, maxLen=1 2 Compare Adjacent If nums[i] > nums[i-1]: inc++ 3 Track Decreasing If nums[i] < nums[i-1]: dec++ 4 Update Max maxLen = max(maxLen, inc, dec) State Tracking Table: i val inc dec max 1 4 2 1 2 2 3 1 2 2 3 3 1 1 2 4 2 1 2 2 FINAL RESULT Longest Subarray Found: Increasing 1 4 Decreasing 3 2 Output: 2 OK - Length = 2 Multiple subarrays of length 2 exist: [1,4] - increasing [4,3], [3,2] - decreasing Key Insight: Track two counters (inc and dec) simultaneously in a single pass. When comparing adjacent elements, increment the appropriate counter or reset to 1 if equal. This achieves O(n) time and O(1) space complexity. TutorialsPoint - Longest Strictly Increasing or Strictly Decreasing Subarray | Single Pass with State Tracking
Asked in
Google 25 Amazon 18 Microsoft 12
25.0K Views
Medium Frequency
~15 min Avg. Time
850 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