Continuous Subarrays Problem
Description
LeetCode Problem 2762.
You are given a 0-indexed integer array nums. A subarray of nums is called continuous if:
- Let
i,i + 1, ...,jbe the indices in the subarray. Then, for each pair of indicesi <= i_1, i_2 <= j,0 <= |nums[i_1] - nums[i_2]| <= 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:
Continuous subarray of size 1: [5], [4], [2], [4].
Continuous subarray of size 2: [5,4], [4,2], [2,4].
Continuous subarray of size 3: [4,2,4].
There are no subarrys of size 4.
Total continuous subarrays = 4 + 3 + 1 = 8.
It can be shown that there are no more continuous subarrays.
Example 2:
Input: nums = [1,2,3]
Output: 6
Explanation:
Continuous subarray of size 1: [1], [2], [3].
Continuous subarray of size 2: [1,2], [2,3].
Continuous subarray of size 3: [1,2,3].
Total continuous subarrays = 3 + 2 + 1 = 6.
Constraints:
1 <= nums.length <= 10^51 <= nums[i] <= 10^9
Solution
Approach: Sliding Window with an Ordered Multiset
Keep a window nums[i..j] whose largest and smallest values differ by at most 2. Every subarray ending at j and starting inside the window is continuous, so each j adds j - i + 1 to the answer.
For each new nums[j], add it to a multiset (a map from value to count). While the maximum minus the minimum exceeds 2, remove nums[i] and move i right. Because the values in a valid window span at most 3 consecutive integers, the Python, JavaScript and Go versions use a plain hash map and take max/min over its few keys.
Complexity: O(n log n) time with an ordered multiset (O(n) with the small hash map) and O(n) space.
class Solution:
def continuousSubarrays(self, nums: List[int]) -> int:
ans = i = 0
cnt = {} # value -> occurrences in the window; at most 3 distinct values
for j, x in enumerate(nums):
cnt[x] = cnt.get(x, 0) + 1
while max(cnt) - min(cnt) > 2:
y = nums[i]
i += 1
cnt[y] -= 1
if cnt[y] == 0:
del cnt[y]
ans += j - i + 1
return ans