Skip to content

Instantly share code, notes, and snippets.

@Ifihan
Created February 3, 2025 22:00
Show Gist options
  • Save Ifihan/b66e336126f491ab44c11bc0fc460252 to your computer and use it in GitHub Desktop.
Save Ifihan/b66e336126f491ab44c11bc0fc460252 to your computer and use it in GitHub Desktop.
Longest Strictly Increasing or Strictly Decreasing Subarray

Question

Approach

My first approach was to traverse forward and backward to check the longest monotonic subarray but this approach will take a long time as I will have to traverse twice. Instead, I'll used two pointer.

I used two variables, inc_len and dec_len, to track the length of the current increasing and decreasing subarrays, respectively. As I traverse the array, I compare each element with the previous one. If the current element is greater, I increment inc_len and reset dec_len to 1. If it is smaller, I increment dec_len and reset inc_len to 1. If they are equal, I reset both counters to 1.

Implementation

class Solution:
    def longestMonotonicSubarray(self, nums: List[int]) -> int:
        if not nums:
            return None

        inc_len, dec_len = 1, 1
        max_len = 1

        for i in range(1, len(nums)):
            if nums[i] > nums[i - 1]:
                inc_len += 1
                dec_len = 1  
            elif nums[i] < nums[i - 1]: 
                dec_len += 1
                inc_len = 1 
            else: 
                inc_len, dec_len = 1, 1

            max_len = max(max_len, inc_len, dec_len)
        
        return max_len

Complexities

  • Time: O(n)
  • Space: O(1)
image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment