LeetCode solutions

2868. Continuous Subarrays

My accepted Python solution to LeetCode problem 2868, Continuous Subarrays, running in 608ms.

  • Difficulty: Medium
  • Python
  • Runtime 608ms
  • Memory 27.2MB

Read the problem on LeetCode View on GitHub

Python

Accepted on LeetCode — runtime 608ms, memory 27.2MB, accepted 2026-01-01.

python
class Solution:
    def continuousSubarrays(self, nums: List[int]) -> int:
        from collections import deque
        
        n = len(nums)
        result = 0
        left = 0
        
        # Maintain min and max in window
        min_deque = deque()  # Stores indices, increasing values
        max_deque = deque()  # Stores indices, decreasing values
        
        for right in range(n):
            # Update max deque
            while max_deque and nums[max_deque[-1]] <= nums[right]:
                max_deque.pop()
            max_deque.append(right)
            
            # Update min deque
            while min_deque and nums[min_deque[-1]] >= nums[right]:
                min_deque.pop()
            min_deque.append(right)
            
            # Shrink window while max - min > 2
            while nums[max_deque[0]] - nums[min_deque[0]] > 2:
                left += 1
                while max_deque and max_deque[0] < left:
                    max_deque.popleft()
                while min_deque and min_deque[0] < left:
                    min_deque.popleft()
            
            # All subarrays ending at right with start in [left, right] are valid
            result += right - left + 1
        
        return result

Source