Continuous Subarrays — LeetCode 2762 Python Solution

MediumQueueArrayOrdered SetSliding WindowMonotonic QueueHeap (Priority Queue)
Problem
#2762
Reading time
2 min

The problem

You are given a 0-indexed integer array nums. A subarray of nums is called continuous if: Let i, i + 1, ..., j be the indices in the subarray.

Example

Input
nums = [5,4,2,4]
Output
8
Explanation
Continuous subarray of size 1: [5], [4], [2], [4].

Python solution

Python
class Solution:
    def continuousSubarrays(self, nums: List[int]) -> int:
        ans = i = 0
        sl = SortedList()
        for x in nums:
            sl.add(x)
            while sl[-1] - sl[0] > 2:
                sl.remove(nums[i])
                i += 1
            ans += len(sl)
        return ans

Complexity

MeasureComplexity
TimeO(n \times \log n)
SpaceO(n), where n is the length of the array nums auxiliary

Pattern: Sliding Window

Collapse a nested loop over every subarray into a single pass with two indices. LeetCode 2762. Continuous Subarrays is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Sliding Window.

The sliding window guide has the Python template for the pattern and the 116 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2762. Continuous Subarrays?
LeetCode 2762. Continuous Subarrays is rated Medium on LeetCode.
What is the time complexity of LeetCode 2762. Continuous Subarrays?
The Python solution on this page runs in O(n \times \log n).
What is the space complexity of LeetCode 2762. Continuous Subarrays?
The Python solution on this page uses O(n), where n is the length of the array nums auxiliary space.
What topics does LeetCode 2762. Continuous Subarrays cover?
LeetCode 2762. Continuous Subarrays is tagged Queue, Array, Ordered Set, Sliding Window, Monotonic Queue and Heap (Priority Queue) on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview