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. Then, for each pair of indices i <= i1, i2 <= j, we have 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.

Input & Output

Example 1 — Basic Case
$ Input: nums = [5,4,2,4]
Output: 8
💡 Note: Valid subarrays: [5], [4], [2], [4], [5,4], [4,2], [2,4], [4,2,4]. Invalid: [5,4,2] and [5,4,2,4] because |5-2|=3>2 → 8 total
Example 2 — Small Array
$ Input: nums = [1,2,3]
Output: 6
💡 Note: All subarrays are continuous: [1], [2], [3], [1,2], [2,3], [1,2,3] → 6 total
Example 3 — Large Differences
$ Input: nums = [1,10,2]
Output: 3
💡 Note: Valid subarrays: [1], [10], [2]. Invalid: [1,10], [10,2], [1,10,2] due to differences >2 → 3 total

Constraints

  • 1 ≤ nums.length ≤ 105
  • -109 ≤ nums[i] ≤ 109

Visualization

Tap to expand
Continuous Subarrays INPUT Array: nums 5 i=0 4 i=1 2 i=2 4 i=3 Continuous Condition: |nums[i1] - nums[i2]| <= 2 for all pairs in subarray Valid Subarrays Example: [5,4] OK: |5-4|=1 <= 2 [5,4,2] NO: |5-2|=3 > 2 ALGORITHM STEPS 1 Sliding Window Use two pointers: left, right 2 Track Min/Max Use deques for window extremes 3 Expand Right Add element, update deques 4 Shrink if Invalid Move left while max-min > 2 Window Processing: 5 4 2 4 Count subarrays ending at right: count += (right - left + 1) Each valid window adds new subarrays FINAL RESULT All Continuous Subarrays: [5] OK [4] OK [2] OK [4] OK [5,4] OK [4,2] OK [2,4] OK [4,2,4] OK [5,4,2] NO [5,4,2,4] NO + 2 more: [5,4], [4,4] Output: 10 Key Insight: Sliding window with monotonic deques tracks min/max efficiently. For each valid window ending at index 'right', all subarrays starting from 'left' to 'right' are continuous. Count = (right - left + 1). Time: O(n), Space: O(n) - each element enters/exits deques at most once. TutorialsPoint - Continuous Subarrays | Optimal Solution (Sliding Window)
Asked in
Google 25 Amazon 18 Microsoft 15
32.0K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen