#3105

Longest Strictly Increasing or Strictly Decreasing Subarray

Easy
ArrayTwo PointersSliding WindowArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

Instead of checking all subarrays, we can traverse the array once while keeping track of the current length of increasing or decreasing sequences. This reduces the number of checks significantly.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize two variables to track the current length of increasing and decreasing sequences.
  2. 2Step 2: Traverse the array and compare each element with the previous one.
  3. 3Step 3: If the current element is greater than the previous, increment the increasing length; if less, increment the decreasing length; otherwise, reset both lengths to 1.
  4. 4Step 4: Update the maximum length found during the traversal.
solution.py16 lines
1def longest_subarray(nums):
2    max_length = 1
3    inc_length = 1
4    dec_length = 1
5    for i in range(1, len(nums)):
6        if nums[i] > nums[i - 1]:
7            inc_length += 1
8            dec_length = 1
9        elif nums[i] < nums[i - 1]:
10            dec_length += 1
11            inc_length = 1
12        else:
13            inc_length = 1
14            dec_length = 1
15        max_length = max(max_length, inc_length, dec_length)
16    return max_length

Complexity note: The time complexity is O(n) because we only traverse the array once, making it much more efficient than the brute-force approach. The space complexity is O(1) since we are using a constant amount of extra space.

  • 1Identifying patterns in sequences can help reduce the number of checks needed.
  • 2Tracking lengths of sequences can simplify the problem significantly.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.