Continuous Subarrays — LeetCode 2762 Python Solution
MediumQueueArrayOrdered SetSliding WindowMonotonic QueueHeap (Priority Queue)
- Problem
- #2762
- Pattern
- Sliding Window
- Reading time
- 2 min
- Source
- leetcode.com
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n \times \log n) |
| Space | O(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
LeetCode 1438Longest Continuous Subarray With Absolute Diff Less Than or Equal to LimitMediumLeetCode 239Sliding Window MaximumHardLeetCode 1499Max Value of EquationHardLeetCode 2444Count Subarrays With Fixed BoundsHardLeetCode 2760Longest Even Odd Subarray With ThresholdEasyLeetCode 643Maximum Average Subarray IEasy
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.