Continuous Subarrays - Problem
๐ฏ Count Continuous Subarrays
You're given a 0-indexed integer array nums. Your task is to find the total number of continuous subarrays.
A subarray is called continuous if for any two elements in the subarray, their absolute difference is at most 2. In other words, if we have indices i, i+1, ..., j in the subarray, then for every pair of indices i1, i2 where i โค i1, i2 โค j, we need |nums[i1] - nums[i2]| โค 2.
Example: In array [5, 4, 2, 4], the subarray [5, 4] is continuous because |5-4| = 1 โค 2, but [5, 4, 2] is not continuous because |5-2| = 3 > 2.
Return the total count of all such continuous subarrays.
Input & Output
example_1.py โ Basic Case
$
Input:
[5, 4, 2, 4]
โบ
Output:
8
๐ก Note:
The continuous subarrays are: [5], [4], [2], [4], [5,4], [2,4], [4,2], [4,2,4]. Total count = 8. Note that [5,4,2] is not continuous because |5-2| = 3 > 2.
example_2.py โ All Same Elements
$
Input:
[1, 1, 1]
โบ
Output:
6
๐ก Note:
When all elements are the same, every possible subarray is continuous. For array of length n, total subarrays = n*(n+1)/2 = 3*4/2 = 6. The subarrays are: [1], [1], [1], [1,1], [1,1], [1,1,1].
example_3.py โ Single Element
$
Input:
[1]
โบ
Output:
1
๐ก Note:
With only one element, there's exactly one subarray: [1]. Single element subarrays are always continuous.
Constraints
- 1 โค nums.length โค 105
- 1 โค nums[i] โค 109
- Important: The absolute difference condition must hold for ALL pairs in the subarray, not just adjacent elements
Visualization
Tap to expand
Understanding the Visualization
1
Setup Quality Station
Place chocolates on conveyor belt with weight sensors
2
Sliding Quality Window
Use a quality window that expands when weights are within range
3
Track Min/Max Efficiently
Use specialized sensors (deques) to quickly know lightest and heaviest chocolate in current group
4
Count Valid Groups
For each position, count all valid groups ending at that chocolate
Key Takeaway
๐ฏ Key Insight: Instead of checking every pair in every subarray (O(nยณ)), we use sliding window with efficient min/max tracking to achieve O(n) time complexity. The deques maintain sorted order of indices, allowing us to quickly determine if the current window satisfies the continuity condition.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code