Longest Strictly Increasing or Strictly Decreasing Subarray

Easy · Arrays & Hashing · Explanation and code example

Iteration - III

How it works

Another variation uses a single counter and checks if the current direction matches the direction at the start of the current subarray. By comparing the relationship between elements at the subarray's start with the relationship at the current position, we can determine if we're still following the same monotonic pattern.

Steps

  1. Initialize curLen = 1 and res = 1.
  2. For each index i from 1 to n-1:
    • If elements are equal, or if the direction at position i-curLen differs from the direction at position i-1:
      • Reset curLen to 1 (if equal) or 2 (if different direction).
      • Continue to the next iteration.
    • Otherwise, increment curLen and update res = max(res, curLen).
  3. Return res.

Complexity

  • Time complexity: O(n)
  • Space complexity: O(1)

Things to watch for

Ignoring Equal Consecutive Elements

The problem asks for strictly increasing or strictly decreasing subarrays. Equal consecutive elements (nums[i] == nums[i-1]) break both patterns. A common mistake is treating equal elements as continuing the current sequence. When you encounter equal elements, you must reset your counter to 1 because a single element is a valid subarray of length 1.

Forgetting to Track Both Directions

You need to find the longest subarray that is either strictly increasing OR strictly decreasing. A common error is only tracking one direction and missing the optimal answer. Either maintain two separate counters (one for increasing, one for decreasing) or use a direction flag that resets when the pattern changes.

Python code example

from typing import List

class Solution:
    def longestMonotonicSubarray(self, nums: List[int]) -> int:
        curLen = res = 1

        for i in range(1, len(nums)):
            if (nums[i] == nums[i - 1] or
                ((nums[i - curLen] < nums[i - curLen + 1]) != (nums[i - 1] < nums[i]))
            ):
                curLen = 1 if (nums[i] == nums[i - 1]) else 2
                continue

            curLen += 1
            res = max(res, curLen)

        return res

C++ code example

class Solution {
public:
    int longestMonotonicSubarray(vector<int>& nums) {
        int curLen = 1, res = 1;

        for (int i = 1; i < nums.size(); i++) {
            if (nums[i] == nums[i - 1] ||
                ((nums[i - curLen] < nums[i - curLen + 1]) != (nums[i - 1] < nums[i]))) {
                curLen = (nums[i] == nums[i - 1]) ? 1 : 2;
                continue;
            }

            curLen++;
            res = max(res, curLen);
        }

        return res;
    }
};
Source and license

Adapted from NeetCode’s source · MIT license. Node types are supplied by LeetCode where needed.

Your recall check is in progress. Write your attempt before revealing the explanation.

Resume recall check

Browse all problem explanations