15% off all plans & roadmaps Use code
See plansContinuous Subarrays
- LeetCode 2762
- Medium
- Sliding Window
- Variable Size (Condition-Based)
Updated
TL;DR: Count every subarray whose largest and smallest values differ by at most 2. Keep the window's maximum and minimum in two monotonic deques, and move the left edge forward whenever the gap grows past 2.
Problem
You are given a 0-indexed integer array nums. A subarray is called continuous when, for every pair of indices i1 and i2 inside it, 0 <= |nums[i1] - nums[i2]| <= 2.
Return the total number of continuous subarrays.
A subarray is a contiguous non-empty sequence of elements within an array.
Example 1
Input: nums = [5,4,2,4] Output: 8 Explanation: The continuous subarrays of size 1 are [5], [4], [2] and [4]. The size 2 ones are [5,4], [4,2] and [2,4]. The only size 3 one is [4,2,4]. No subarray has size 4. The total is 4 + 3 + 1 = 8, and no other subarray qualifies.
Example 2
Input: nums = [1,2,3] Output: 6 Explanation: The continuous subarrays of size 1 are [1], [2] and [3]. The size 2 ones are [1,2] and [2,3]. The only size 3 one is [1,2,3]. The total is 3 + 2 + 1 = 6.
Constraints
1 <= nums.length <= 10^51 <= nums[i] <= 10^9
Constraints that matter
- n up to 10^5 rules out checking every subarray with a fresh scan, which is O(n^3) work.
- n up to 10^5 also rules out O(n^2) pair checks, since about 5 * 10^9 steps is far too many.
- The values can be up to 10^9, so the gap must be compared with 2 directly. Hashing by value range does not help.
- The answer can reach about 5 * 10^9, so the total needs a 64-bit counter in languages that check overflow.
Hints
Hint 1
The problem asks for a count, but the count comes from windows.
Hint 2
The naive solution tests every subarray.
Solution
Intuition
The problem asks for a count, but the count comes from windows. A subarray is continuous exactly when its largest and smallest values differ by at most 2. Every pairwise difference is bounded by that gap, so you only need to track two numbers per window.
Picture a line of people where you must always know the tallest and shortest person present. The max deque is a row of people who could still be tallest later, and its front is the tallest one right now.
Sub-windows of a valid window are also valid. If nums[L..R] is continuous, removing elements from either end cannot widen the range. So every nums[k..R] with L <= k <= R is continuous too.
For a fixed right end R, the valid starts form a block ending at R. The first valid start only moves right as R grows. This is the variable-size sliding window pattern: expand the right edge, and shrink the left edge only when the window breaks.
Each right end R contributes R - left + 1 subarrays, one for each valid start. The hard part is keeping the window's maximum and minimum current while elements leave from the left. A plain variable holds the maximum, but it cannot recover the next maximum after the old one leaves. A monotonic deque keeps only the candidates that could still be the maximum later. Its front is always the current maximum.
Recognise this shape when a question asks for a count of subarrays with a property that survives trimming from the ends.
Worked example
Input: nums = [2, 4, 3, 1, 2] Output: 11 Explanation: There are 5 single elements, 4 pairs ([2,4], [4,3], [3,1], [1,2]) and 2 triples ([2,4,3], [3,1,2]). Every longer subarray contains a gap of 3, so it fails. The total is 5 + 4 + 2 = 11.
Approach 1: Brute force
The naive solution tests every subarray. For each start index i and end index j, it scans nums[i..j] to find the smallest and largest values, then checks the gap. Nothing is reused between subarrays, so the same elements are scanned again and again. Each test costs up to n steps, and there are about n^2 / 2 tests.
Steps
- Set count to 0.
- For each start index i from 0 to n - 1, loop over each end index j from i to n - 1.
- Scan nums[i..j] and record the smallest value lo and the largest value hi.
- If hi - lo is at most 2, add 1 to count.
- Return count.
Dry run
Start at i = 0 and check each end index on [2, 4, 3, 1, 2]. The subarrays [2], [2, 4] and [2, 4, 3] pass with gaps 0, 2 and 2. The subarray [2, 4, 3, 1] has gap 3 and fails, and so does [2, 4, 3, 1, 2].
Start i = 1 passes [4] and [4, 3], adding 2. Start i = 2 passes [3], [3, 1] and [3, 1, 2], adding 3. Start i = 3 passes [1] and [1, 2], adding 2. Start i = 4 passes [2], adding 1. The total is 3 + 2 + 3 + 2 + 1 = 11.
Complexity
| Time | O(n^3) |
|---|---|
| Space | O(1) |
Let n be the length of nums. There are about n^2 / 2 pairs (i, j), and the scan for each pair costs j - i + 1 steps. Summing those scan lengths over all pairs gives about n^3 / 6 steps, so the time is O(n^3). The loop stores only a few integers, so the extra space is O(1).
PythonTested in our runner
class Solution:
def continuousSubarrays(self, nums: List[int]) -> int:
n = len(nums)
count = 0
for i in range(n):
for j in range(i, n):
window = nums[i:j + 1]
if max(window) - min(window) <= 2:
count += 1
return countApproach 2: Running min and max per start
What is slow: the brute force scan rebuilds the minimum and maximum for every pair. When j moves one step right, the subarray gains only one element, so the old minimum and maximum still cover the rest. The insight that fixes it is to keep lo and hi while j grows, updating each with one comparison. Also, once the gap exceeds 2 at some j, every longer subarray starting at i contains the same pair and fails, so the inner loop can stop.
Steps
- Set count to 0.
- For each start index i, set lo and hi to nums[i].
- Loop j from i to n - 1. Update lo with min(lo, nums[j]) and hi with max(hi, nums[j]).
- If hi - lo is greater than 2, break out of the inner loop.
- Otherwise add 1 to count.
- Return count.
Dry run
Start at i = 0. The values keep a gap of at most 2 for j = 0, 1 and 2, adding 3 subarrays. At j = 3 the value 1 pushes the gap to 3, so the loop breaks. Start at i = 1 adds 2 for [4] and [4, 3], then breaks at j = 3. Start at i = 2 never breaks and adds 3. Start at i = 3 adds 2. Start at i = 4 adds 1. The total is 3 + 2 + 3 + 2 + 1 = 11.
Complexity
| Time | O(n^2) |
|---|---|
| Space | O(1) |
The outer loop runs n times. For start i, the inner loop runs at most n - i times before it breaks or reaches the end. The total is at most n + (n - 1) + ... + 1 = n(n + 1) / 2 steps, each with constant work, so the time is O(n^2). The code stores only lo, hi and count, so the space is O(1).
PythonTested in our runner
class Solution:
def continuousSubarrays(self, nums: List[int]) -> int:
n = len(nums)
count = 0
for i in range(n):
lo = hi = nums[i]
for j in range(i, n):
lo = min(lo, nums[j])
hi = max(hi, nums[j])
if hi - lo > 2:
break # longer subarrays from i fail too
count += 1
return countThe Variable Size (Condition-Based) infographic is part of Pro
A one-page visual of the pattern: when it applies, the steps and the invariant to keep.
Unlock the infographicSolution pattern
Variable Size (Condition-Based)
Part of Sliding Window
Approach 3: Sliding window with monotonic dequesOptimalVariable Size (Condition-Based)
What is slow: the running scan restarts from every start index, so each right end rescans elements that were already seen for the previous start. The insight that fixes it is one window whose left and right edges only move forward.
Two monotonic deques track the maximum and the minimum. The max deque keeps indices with decreasing values, so its front is the window maximum. The min deque keeps indices with increasing values, so its front is the window minimum. When left moves past a front index, that index leaves the deque.
Steps
- Create index arrays maxQ and minQ with head and tail pointers. Set left and count to 0.
- For each right index, pop from the back of maxQ while its value is at most nums[right], then push right. Do the same for minQ, popping while its value is at least nums[right].
- While the front of maxQ minus the front of minQ is greater than 2, increase left by 1.
- After moving left, pop the front of maxQ or minQ when that front index is less than left.
- Add right - left + 1 to count.
- Return count.
Dry run
The table shows the state after each right index. The max deque lists index:value pairs from front to back, and the same for the min deque.
| right | value | maxQ | minQ | left | gap | count |
|---|---|---|---|---|---|---|
| 0 | 2 | 0:2 | 0:2 | 0 | 0 | 1 |
| 1 | 4 | 1:4 | 0:2, 1:4 | 0 | 2 | 3 |
| 2 | 3 | 1:4, 2:3 | 0:2, 2:3 | 0 | 2 | 6 |
| 3 | 1 | 2:3, 3:1 | 3:1 | 2 | 2 | 8 |
| 4 | 2 | 2:3, 4:2 | 3:1, 4:2 | 2 | 2 | 11 |
At right = 3 the gap starts at 3 (4 minus 1). Moving left to 1 removes nothing, so the gap stays 3. Moving left to 2 pops index 1 from the front of maxQ, and the gap drops to 2. The final count is 11.
Complexity
| Time | O(n) |
|---|---|
| Space | O(n) |
Let n be the length of nums. Each index is pushed once into each deque and popped at most once from the back and once from the front. The left edge moves at most n times in total, so the shrink loop does at most n checks, and total work is O(n) time. The deques can hold up to n indices, for example when the array is strictly increasing and minQ keeps every index, so the space is O(n).
PythonTested in our runner
class Solution:
def continuousSubarrays(self, nums: List[int]) -> int:
n = len(nums)
max_q = [0] * n # indices, values decreasing
min_q = [0] * n # indices, values increasing
max_h = max_t = 0
min_h = min_t = 0
left = 0
count = 0
for right in range(n):
while max_t > max_h and nums[max_q[max_t - 1]] <= nums[right]:
max_t -= 1
max_q[max_t] = right
max_t += 1
while min_t > min_h and nums[min_q[min_t - 1]] >= nums[right]:
min_t -= 1
min_q[min_t] = right
min_t += 1
# the window max and min sit at the fronts of the two deques
while nums[max_q[max_h]] - nums[min_q[min_h]] > 2:
left += 1
if max_q[max_h] < left:
max_h += 1
if min_q[min_h] < left:
min_h += 1
count += right - left + 1
return countCommon mistakes
max_q.append(right)with no back pops in the max deque. The front then holds the oldest index, not the maximum. Pop every tail whose value is at mostnums[right]before pushing.ifinstead ofwhileon the shrink check. On [2, 4, 3, 1, 2], right = 3 needs two moves of left before the gap is 2. Withif, the window stays invalid and the count adds too many subarrays.- Counting
right - leftinstead ofright - left + 1. The single-element subarray ending at right is lost, and the first example returns 10 instead of 11. - Skipping the front pop, so the deque still lists an index below
left. The gap then uses a value that is no longer in the window. Pop the front when its index is less thanleft. - Keeping the window max and min in two scalar variables. When the old maximum leaves from the left, the code cannot find the next largest value. Use the deques instead.
Edge cases
- A single element such as [7] returns 1.
- All values equal, such as [5, 5, 5, 5], makes every subarray valid. The answer is 10, which is 4 * 5 / 2.
- A gap of exactly 2 passes and a gap of 3 fails. [1, 3] returns 3, and [1, 4] returns 2.
- A strictly increasing run such as [1, 2, 3, 4] returns 9. Size 1 gives 4, size 2 gives 3, size 3 gives 2, and size 4 fails with gap 3.
- Large values such as [1000000000, 999999999, 999999998] return 6. The gap fits in a 32-bit int because the values are at most 10^9.
- All values equal with n = 10^5 gives 5000050000, which is above 2^31 - 1. The starter signature returns int, so the Java, C++ and C# solutions truncate that total. Python is exact. A 64-bit return type is needed for those inputs.
Follow-ups interviewers ask
Follow-ups are part of Pro
The questions interviewers ask after you solve Continuous Subarrays, with how to answer them.
Unlock the follow-upsContinuous Subarrays FAQ
What is the time complexity of Continuous Subarrays?
The deque solution runs in O(n) time, where n is the array length. The running-scan solution runs in O(n^2), and the brute force runs in O(n^3). The deque version handles each index a bounded number of times.
Why use a sliding window for Continuous Subarrays?
A valid subarray stays valid when you trim it from either end. So the left edge only moves forward, and each right end adds a whole block of valid subarrays at once.
Why use a monotonic deque for Continuous Subarrays?
The window needs its maximum and minimum after elements leave from the left. A monotonic deque keeps the candidates in order, so its front holds the current extreme. Each index enters and leaves the deque at most once.
Can Continuous Subarrays be solved in O(1) extra space?
Yes. Keep a hash map of value counts for the window, since a valid window has at most 3 distinct values and the map never holds more than 4 keys. The deque version uses O(n) space in the worst case, such as a strictly increasing array.
Does the continuous subarrays Python solution overflow?
No. Python integers have arbitrary precision, so the total stays exact even above 2^31 - 1. In Java, C++ and C#, the starter signature returns int, so totals above 2^31 - 1 need a 64-bit return type to be exact.
Asked at
See which companies ask this — Pro
Related problems
- Longest Substring Without Repeating Characters · same technique: Variable Size (Condition-Based)
- Longest Repeating Character Replacement · same technique: Variable Size (Condition-Based)
- Minimum Size Subarray Sum · same technique: Variable Size (Condition-Based)
- Longest Turbulent Subarray · same technique: Variable Size (Condition-Based)
- Jump Game VII · same technique: Variable Size (Condition-Based)
- Max Consecutive Ones III · same technique: Variable Size (Condition-Based)
- Minimum Window Substring · next harder, same pattern
- Permutation in String · same pattern: Sliding Window
- Find All Anagrams in a String · same pattern: Sliding Window
- Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit · same pattern: Sliding Window