We are given an array of integers nums and an integer k. We need to count the number of contiguous subarrays such that the range (max - min) of the subarray equals exactly k.
This is a classic problem that can be solved using two pointers and some data structures (like monotonic deques) to track min and max in a sliding window. However, the condition is "exactly k", and we want to count all subarrays with range exactly k.
One common approach: Count subarrays with range <= k and subtract those with range <= k-1. That is, if we can compute f(L) = number of subarrays with range <= L, then answer = f(k) - f(k-1). This is a standard technique for "exactly equal to" problems.
So we need to compute f(L) efficiently: number of subarrays where max - min <= L.
We can use a sliding window with two pointers. For each left index, we find the rightmost index such that the window [left, right] satisfies max - min <= L. Then, all subarrays starting at left and ending at any index from left to that right index are valid. So for each left, we count (right - left + 1). But we need to maintain the max and min efficiently as we move left and right. We can use two deques: one for max (decreasing) and one for min (increasing). As we extend right, we update the deques. When the condition fails (max - min > L), we move left forward, popping from deques as necessary, until condition holds again.
Implementation:
Initialize left = 0, right = 0. For each left from 0 to n-1:
While right < n and window [left, right] satisfies max - min <= L (we check after adding nums[right]), we add nums[right] to deques and increment right.
But careful: We want to find the maximum right such that condition holds for current left. So we can move right as far as possible while condition holds. Then the number of subarrays starting at left is (right - left). Because when we break, right is the first index where condition fails? Actually, we typically do: for left in range(n):
while right < n and condition holds for window [left, right] after including nums[right]:
add nums[right] to deques, right++
Then count += right - left
Then before incrementing left, we remove nums[left] from deques if they are at the front.
But careful: The condition check should be: when we are about to include nums[right], we check if after including it, max - min <= L. So we need to update deques for right and then check condition. If condition fails, we break without incrementing right? Actually, we should only increment right if condition holds. So:
while right < n:
add nums[right] to deques (update maxDeque and minDeque)
if maxDeque[0] - minDeque[0] <= L:
right += 1
else:
break? But we have already added nums[right]. We need to revert? Actually, we can check condition after adding. If condition fails, we should not include that right. So we need to not add it? But we already added. So better to check before adding? We can compute the new max and min if we add nums[right] without actually adding? That's messy.
Alternate approach: We maintain the deques for the current window [left, right). Initially, window is empty. We want to extend right as long as condition holds. So:
while right < n:
Let candidate = nums[right]
We need to compute new max and min if we include candidate. But we can simulate by looking at current max and min and candidate. Actually, we can add candidate to the deques, then check condition. If condition fails, we break and then we will have added candidate, but we don't want to include it. So we need to pop it? That's inefficient.
Better: Use a while loop that extends right and updates deques, but after updating we check condition. If condition fails, we break and then we need to revert the addition? Not necessary if we design carefully.
Common pattern:
Initialize left = 0, right = 0.
for left in range(n):
while right < n and condition holds for window [left, right] after including nums[right]:
add nums[right] to deques
right += 1
count += right - left
then remove nums[left] from deques if they are at the front.
But the condition "holds for window [left, right] after including nums[right]" means we need to consider the window that includes nums[right]? Actually, at the start of the while loop, right points to the next element to include. So we want to check if we include nums[right], does condition hold? But we haven't included it yet. So we can compute the potential new max and min by looking at current deques (which represent window [left, right)) and nums[right]. The new max would be max(current max, nums[right]), new min would be min(current min, nums[right]). But we have deques that store the max and min in the current window. So we can compute:
new_max = max(maxDeque[0] if maxDeque else -inf, nums[right])
new_min = min(minDeque[0] if minDeque else inf, nums[right])
But that's not exactly correct because the maxDeque[0] is the maximum of current window. However, if we add a new element, the max could be either that or nums[right]. Similarly for min. So condition: new_max - new_min <= L.
But we also need to update the deques for the next iteration if we decide to include. So we can do:
while right < n:
# compute potential new max and min
temp_max = max(maxDeque[0] if maxDeque else nums[right], nums[right])? Actually, if maxDeque is not empty, the current max is maxDeque[0]. But if we add nums[right], the new max is max(maxDeque[0], nums[right]).
Similarly, new_min = min(minDeque[0] if minDeque else nums[right], nums[right]).
if new_max - new_min <= L:
# then we include nums[right]
add nums[right] to deques (update both)
right += 1
else:
break
But note: The deques are for the current window [left, right). After we add nums[right], the window becomes [left, right+1). So we need to update deques accordingly. But the condition check uses the deques as they are (current window) and nums[right]. That's fine.
However, we must be cautious: The maxDeque and minDeque are maintained such that they contain the indices? Usually we store indices to know when to pop when left moves. But we can also store values, but then when we move left we need to know if the value at left is the same as the front of deque. So it's easier to store indices.
So let's design:
We have two deques: maxDeque (decreasing) and minDeque (increasing). They store indices of elements in the current window [left, right).
We start with left=0, right=0, window empty.
For each left from 0 to n-1:
while right < n:
# let i = right
# we want to check if we can add nums[right] without violating condition.
# Compute new max and new min hypothetically:
if maxDeque: current_max = nums[maxDeque[0]]
else: current_max = -inf? Actually, if window is empty, then current_max and current_min are undefined. But we are about to add the first element. So we can handle separately: if right==left, then window is empty, so adding first element always satisfies because max-min=0 <= L (if L>=0). But k can be negative? The range is max-min, so it's non-negative. k is given, so if k is negative, no subarray can have range negative. But we assume k>=0. So L (the parameter) is non-negative. So for empty window, condition holds trivially. But we are checking condition after adding one element: range=0 <= L always true if L>=0. So we can just include.
But to unify, we can do:
while right < n:
# Let i = right
# We need to compute the new max and min if we include i.
# We can get current max from maxDeque[0] if maxDeque else nums[i]? Actually, if maxDeque is empty, current window is empty, so after adding nums[i], the max and min are both nums[i]. So condition holds.
# But we can do:
new_max = nums[i]
new_min = nums[i]
if maxDeque:
new_max = max(new_max, nums[maxDeque[0]])
if minDeque:
new_min = min(new_min, nums[minDeque[0]])
if new_max - new_min <= L:
# include i
# update deques for including i
while maxDeque and nums[maxDeque[-1]] <= nums[i]:
maxDeque.pop()
maxDeque.append(i)
while minDeque and nums[minDeque[-1]] >= nums[i]:
minDeque.pop()
minDeque.append(i)
right += 1
else:
break
After this while, we have that the window [left, right) (i.e., from left to right-1) satisfies condition. So the number of subarrays starting at left is (right - left). Because any subarray [left, end] with end from left to right-1 is valid.
Then we need to remove left from the deques if they are at the front. Since left is about to increment, we check:
if maxDeque and maxDeque[0] == left:
maxDeque.popleft()
if minDeque and minDeque[0] == left:
minDeque.popleft()
Then left++ (in the for loop, we are iterating left, so we do this at the end of the loop).
But note: The while loop condition uses the current deques which represent window [left, right). So after we remove left, the deques will represent [left+1, right). That's correct.
This algorithm runs in O(n) because each element is added and removed at most once from each deque.
Now, to compute f(L), we do:
def count_subarrays_with_range_at_most(L):
if L < 0: return 0
n = len(nums)
maxDeque = deque()
minDeque = deque()
left = 0
right = 0
count = 0
for left in range(n):
while right < n:
i = right
# compute potential new max and min
new_max = nums[i]
new_min = nums[i]
if maxDeque:
new_max = max(new_max, nums[maxDeque[0]])
if minDeque:
new_min = min(new_min, nums[minDeque[0]])
if new_max - new_min <= L:
# add i
while maxDeque and nums[maxDeque[-1]] <= nums[i]:
maxDeque.pop()
maxDeque.append(i)
while minDeque and nums[minDeque[-1]] >= nums[i]:
minDeque.pop()
minDeque.append(i)
right += 1
else:
break
count += right - left
# remove left from deques
if maxDeque and maxDeque[0] == left:
maxDeque.popleft()
if minDeque and minDeque[0] == left:
minDeque.popleft()
return count
Then answer = count_subarrays_with_range_at_most(k) - count_subarrays_with_range_at_most(k-1)
But wait: This counts subarrays with range <= L. However, note that when we compute f(k) and f(k-1), we are counting subarrays with range exactly k. But is that correct? Yes, because any subarray with range exactly k is counted in f(k) but not in f(k-1) since its range is not <= k-1. So difference gives exactly k.
But we must be cautious: What about k=0? Then f(-1) = 0, so answer = f(0). That works.
Edge cases: If k is negative? The problem likely expects k>=0. But if k is negative, then no subarray has range equal to negative, so answer=0. We can handle that by returning 0 if k<0.
But also, our f(L) for L<0 returns 0. So if k is negative, f(k)=0 and f(k-1)=0? Actually, if k is negative, then k-1 is more negative. So we would compute f(k) and f(k-1) both 0, difference 0. So it's fine.
But we need to be careful: Our f(L) implementation might assume L>=0. In the while loop, we compute new_max - new_min. That is always non-negative. So if L<0, then condition new_max - new_min <= L will never hold because left side is >=0 and L<0. So the while loop will never add any element? Actually, for the first element, new_max - new_min = 0, which is not <= negative L. So we will break immediately, and then count += right - left? For left=0, right=0 initially, so right-left=0. Then we remove left (but deques are empty). So for every left, right remains 0? Actually, we need to simulate: For left=0, we enter the for loop. Then while right < n: right=0, i=0. new_max = nums[0], new_min = nums[0], difference=0. If L<0, 0 <= L is false. So we break without adding. Then count += 0. Then we remove left from deques (nothing). Then left increments. So we never increment right. So right remains 0 throughout. So f(L) = 0 for L<0. That's correct.
But what about L being very large? Then condition always holds, so right will go to n for left=0, then for subsequent left, we will have right=n, and we will just count n-left for each left. That gives total subarrays n*(n+1)/2. That's correct.
So the algorithm seems sound.
However, there is a nuance: In the while condition, we are checking if we can include nums[right] without violating condition. But note that the current deques represent window [left, right). So the current max and min are from that window. When we consider adding nums[right], the new max is max(current max, nums[right]) and new min is min(current min, nums[right]). That is correct. But what if the current window is empty? Then we don't have current max/min. In that case, we set new_max and new_min to nums[i] and then condition holds because 0 <= L. So it's fine.
But we need to be careful: When we add an element, we update the deques. But what about the case where we break because condition fails? Then we did not add nums[right]. So the deques remain for window [left, right). That's correct.
Now, complexity: Each element is added to and removed from each deque at most once, so O(n).
But wait: There is a potential issue: The while loop that extends right might not run for every left? Actually, in the standard two-pointer for "at most" condition, we usually have a single while loop that moves right forward and never backward. But here, for each left, we start with the current right (from previous iteration) and then possibly extend further. That is the typical implementation. However, note that when we move left forward, the window shrinks from the left, so the condition might become easier, and we might be able to extend right further. But in our code, after we count for left, we remove left and then increment left. Then for the next left, we start with the same right as before? Actually, in the for loop, we have left increasing. But we are not resetting right. So right is monotonic non-decreasing. That is correct because as left increases, the window [left, right) might become smaller, so we can potentially move right forward to compensate. But note: after we remove left, the condition might hold for a larger right? Actually, when we remove an element, the max or min might change, so the condition might become easier, meaning we might be able to include more elements on the right. So we should try to extend right again for the new left. That's exactly what we do: for each new left, we enter the while loop and try to move right as far as possible from its current position. So that's correct.
But there is a subtlety: When we break out of the while loop for a given left, we have that window [left, right) satisfies condition, but adding nums[right] would violate. Then we count right-left. Then we remove left. Now for left+1, the window is [left+1, right). This window might satisfy condition? Possibly yes, because removing an element might reduce max or increase min, so the range might decrease. So it's possible that now we can include nums[right]? But we did not check that. In our code, for the next left, we start with the same right, and then we enter the while loop and check if we can include nums[right] now. So we will check again. That's fine.
So the algorithm is correct.
But we need to be cautious about the computation of new_max and new_min. What if the current window is not empty, but the maxDeque[0] is an index that is less than left? Actually, we maintain deques such that they only contain indices in the current window [left, right). Because when we move left, we pop from the front if the index equals left. So after we remove left, the deques only have indices >= left+1. So at the beginning of the for loop for a given left, the deques represent the window [left, right). That is correct because we just removed the previous left (which was left-1) at the end of the previous iteration. So for the current left, the deques are for window [left, right). So maxDeque[0] is the index of the maximum in that window, and similarly for min. So our computation of new_max and new_min is correct.
Now, what about the initial state? At left=0, right=0, deques are empty. That's fine.
So f(L) is computed correctly.
Then answer = f(k) - f(k-1).
But wait: Is there any subarray that has range exactly k that might be counted in both? No, because if range exactly k, it is <= k but not <= k-1. So difference is exact.
But what about k=0? Then we want subarrays with max-min=0, i.e., all elements equal. f(0) counts all subarrays with max-min <= 0, which means all elements equal. That is exactly what we want. So difference works.
So the solution is to implement two functions? Actually, we can compute f(k) and f(k-1) with the same function by passing L. So we just call count_at_most(k) and count_at_most(k-1) and subtract.
But note: The function count_at_most(L) as we wrote runs in O(n) and uses two pointers. So overall O(n) for each call, so O(n) total? Actually, we call it twice, so O(n) each, total O(n). But careful: The two calls are independent. So total time O(2n) = O(n). That's acceptable.
But is there a way to do it in one pass? Possibly by counting exactly k directly? That might be more complex because we need to maintain both max and min and the condition exactly k. The two-pointer method for "exactly k" typically uses the "at most" difference.
So we'll implement:
def subarray_range(nums, k):
def count_at_most(L):
# as above
return count_at_most(k) - count_at_most(k-1)
But we must handle the case when k is negative? If k<0, then count_at_most(k) and count_at_most(k-1) both return 0, so difference 0. So it's fine.
But what about very large k? Then count_at_most(k) will count all subarrays, which is n*(n+1)/2. That's fine.
Now, we need to write code in Python (assuming). We'll use collections.deque.
Let's test with examples.
Example: nums = [1,2,3], k=1.
Subarrays:
[1]: range=0
[2]:0
[3]:0
[1,2]:1
[2,3]:1
[1,2,3]:2
So exactly k=1: two subarrays.
f(1) = count of subarrays with range <=1: that includes all with range 0 or 1: so [1],[2],[3],[1,2],[2,3] = 5.
f(0) = count with range <=0: only single elements: 3.
Difference = 5-3=2. Correct.
Example: nums = [1,3,2], k=2.
Subarrays:
[1]:0
[3]:0
[2]:0
[1,3]:2
[3,2]:1
[1,3,2]:2 (max=3,min=1,diff=2)
So exactly k=2: [1,3] and [1,3,2] -> 2.
f(2): all subarrays? Check:
[1]:0<=2 yes
[3]:0 yes
[2]:0 yes
[1,3]:2 yes
[3,2]:1 yes
[1,3,2]:2 yes
So all 6 subarrays? Actually, there are 6 subarrays? For n=3, total subarrays = 6. But we listed 6. So f(2)=6.
f(1): subarrays with range <=1: singles (3) and [3,2] (range=1) -> 4.
Difference = 6-4=2. Correct.
Example: nums = [4,1,3,2], k=2.
Let's compute manually? Maybe later.
So algorithm seems correct.
But wait: In the while loop, we compute new_max and new_min by looking at the current max and min from deques. But what if the current window is empty? Then maxDeque is empty, so we set new_max = nums[i] and new_min = nums[i]. That's fine.
But what about when we have multiple elements in deques? The maxDeque[0] is the maximum in the current window. But when we add nums[i], the new maximum is max(current max, nums[i]). That is correct. Similarly for min.
But is it possible that the current maxDeque[0] is not the true maximum because we have not removed some indices that are out of the window? No, because we remove from the front when the index equals left. And we do that at the end of each left iteration. So at the beginning of the left iteration, the deques contain only indices >= left. So they represent the current window [left, right). So maxDeque[0] is indeed the maximum.
Now, one more nuance: When we compute new_max and new_min, we are using the current max and min from deques. But what if we are about to add nums[right] and the current max is from an index that will be removed when we later move left? That doesn't matter because we are checking condition for the new window that includes nums[right]. The new window is [left, right+1) if we include. The current max is from [left, right). So the new max is max(current max, nums[right]). That is correct because the new window includes all current elements plus nums[right]. So the maximum is either the old maximum or nums[right].
But wait: Could it be that the current max is from an element that is not in the window because we haven't removed it yet? No, we maintain deques for the current window. So it's fine.
Thus the algorithm is correct.
Now, we need to implement it carefully.
We'll write:
from collections import deque
def count_at_most(nums, L):
n = len(nums)
if L < 0:
return 0
maxDeque = deque()
minDeque = deque()
left = 0
right = 0
count = 0
for left in range(n):
# Expand right as much as possible
while right < n:
i = right
# compute candidate new max and min
cur_max = nums[maxDeque[0]] if maxDeque else nums[i]
cur_min = nums[minDeque[0]] if minDeque else nums[i]
new_max = max(cur_max, nums[i])
new_min = min(cur_min, nums[i])
if new_max - new_min <= L:
# include i
while maxDeque and nums[maxDeque[-1]] <= nums[i]:
maxDeque.pop()
maxDeque.append(i)
while minDeque and nums[minDeque[-1]] >= nums[i]:
minDeque.pop()
minDeque.append(i)
right += 1
else:
break
count += right - left
# remove left from deques
if maxDeque and maxDeque[0] == left:
maxDeque.popleft()
if minDeque and minDeque[0] == left:
minDeque.popleft()
return count
def subarray_range(nums, k):
return count_at_most(nums, k) - count_at_most(nums, k-1)
But wait: In the while loop, we are using cur_max and cur_min from the current window. But when we add nums[i], we are comparing with cur_max and cur_min. However, note that if the current window is empty (maxDeque empty), we set cur_max = nums[i]. That means new_max = max(nums[i], nums[i]) = nums[i]. Similarly new_min = nums[i]. So condition holds. That's fine.
But what about when the current window is not empty? For example, current window has max=5 and min=2. We want to add nums[i]=3. Then new_max = max(5,3)=5, new_min = min(2,3)=2, difference=3. If L=2, then 3>2, so we break. That's correct.
But consider adding nums[i]=6: new_max=6, new_min=2, diff=4. Might break.
So condition check is correct.
But there is an optimization: Instead of computing new_max and new_min by looking at current max and min, we could directly update the deques and then check condition? But that would require updating deques first, and if condition fails we would have to revert? Not good.
So the above is fine.
But let's test with a simple case: nums=[1,2], L=1.
left=0, right=0, maxDeque=[], minDeque=[].
For left=0:
while right<2:
i=0: cur_max? maxDeque empty -> set to nums[0]=1. cur_min similarly 1. new_max=1, new_min=1, diff=0<=1 -> include.
update deques: maxDeque: push 0 (since empty). minDeque: push 0.
right becomes 1.
now right=1, i=1:
cur_max = nums[maxDeque[0]] = nums[0]=1
cur_min = nums[minDeque[0]] = nums[0]=1
new_max = max(1, nums[1]=2)=2
new_min = min(1,2)=1
diff=1<=1 -> include.
update maxDeque: while last element's value <=2? last is 0 with value 1<=2, so pop. then push 1. So maxDeque=[1].
minDeque: while last element's value >=2? last is 0 with value 1>=2? false, so push. minDeque=[0,1]? Actually, minDeque should be increasing. We push 1, but check: while minDeque and nums[minDeque[-1]] >= nums[1]: nums[0]=1 >=2? false, so we just append. So minDeque becomes [0,1]. But that's not correct for minDeque? Actually, for minDeque, we maintain increasing order? Wait, for min deque we usually maintain increasing order (so that the front is the minimum). But we want the front to be the smallest. So we maintain a deque such that the values are increasing from front to back? Actually, for minimum, we want the front to be the minimum. So we maintain a deque where the values are non-decreasing? Let's think: For the sliding window minimum, we maintain a deque where the front is the minimum and the values in the deque are increasing. When we add a new element, we remove from the back all elements that are greater than or equal to the new element? Actually, to keep the front as the minimum, we want to remove elements from the back that are larger than the new element because they will never be the minimum in the future. So we maintain a deque with increasing values. So condition: while deque and nums[deque[-1]] >= nums[i]: pop. Then append i. That gives a deque with values non-decreasing from front to back? Actually, if we remove all that are >= nums[i], then the remaining are < nums[i], so after appending, the deque values are strictly increasing? Not necessarily strictly, but non-decreasing? Actually, if we remove all that are >= nums[i], then the last element is < nums[i]. So after appending, the deque is strictly increasing? Possibly. But it's fine.
In our example, for minDeque after adding 1: we have [0] with value 1. Then adding 2: nums[0]=1 >=2? false, so we don't pop. Then we append 1. So minDeque becomes [0,1] with values [1,2]. That's increasing. So front is 0 with value 1, which is the minimum. So that's correct.
Now, after including both, right=2.
Then count += right-left = 2-0=2.
Then remove left=0: maxDeque[0]==0? maxDeque=[1] so no. minDeque[0]==0? yes, so pop. minDeque becomes [1].
Then left increments to 1.
Now for left=1:
while right<2? right=2, so no.
count += right-left = 2-1=1.
remove left=1: maxDeque[0]==1? yes, pop. maxDeque empty. minDeque[0]==1? yes, pop. minDeque empty.
So total count = 2+1=3. That is number of subarrays with range <=1: [1],[2],[1,2]? Actually, [1] range0, [2] range0, [1,2] range1. That's 3. Correct.
Now f(0): we expect 2 (only singles). Let's test with L=0.
left=0, right=0.
while right<2:
i=0: cur_max? empty -> set to 1, cur_min=1, diff=0<=0 -> include. deques: maxDeque=[0], minDeque=[0], right=1.
i=1: cur_max = nums[0]=1, cur_min=1, new_max = max(1,2)=2, new_min=min(1,2)=1, diff=1>0 -> break.
count += right-left = 1-0=1.
remove left=0: both deques have 0, so pop. deques empty.
left=1:
while right<2: now right=1, i=1: deques empty, so cur_max=nums[1]=2, cur_min=2, diff=0<=0 -> include. deques: maxDeque=[1], minDeque=[1], right=2.
then while ends.
count += right-left = 2-1=1.
remove left=1: pop from deques.
total count=1+1=2. Correct.
So difference for k=1: f(1)-f(0)=3-2=1? But we expected 2 for k=1? Wait, in the example nums=[1,2], k=1, we have exactly one subarray with range exactly 1? Actually, subarrays: [1] range0, [2] range0, [1,2] range1. So exactly k=1: only [1,2]. So that's 1. But earlier I said for nums=[1,2,3] we had two. So for [1,2] it's 1. So our calculation gave 3-2=1. That's correct.
But wait, I earlier said for nums=[1,2] with k=1, f(1)=3, f(0)=2, difference=1. That matches.
So algorithm is correct.
Now, what about more complex cases? Let's test nums=[1,3,2], k=2.
We computed f(2)=6, f(1)=4, difference=2.
Let's simulate f(2) quickly:
We need to count all subarrays with range <=2. Since max-min for whole array is 2, all subarrays should have range <=2? Check: [1,3] range2, [3,2] range1, [1,3,2] range2. So yes all 6. So f(2)=6.
f(1): subarrays with range <=1: singles (3) and [3,2] (range1) =4. So difference=2. Correct.
Now test with nums=[4,1,3,2], k=2.
List all subarrays:
Indices: 0:4, 1:1, 2:3, 3:2.
Subarrays:
[0]:4 ->0
[1]:1 ->0
[2]:3 ->0
[3]:2 ->0
[0,1]: max4 min1 diff3 >2
[1,2]: max3 min1 diff2 <=2
[2,3]: max3 min2 diff1
[0,1,2]: max4 min1 diff3
[1,2,3]: max3 min1 diff2
[0,1,2,3]: max4 min1 diff3
[0,2]:? That's not contiguous? We only consider contiguous. So we have all contiguous:
Length 2: [0,1], [1,2], [2,3]
Length 3: [0,1,2], [1,2,3]
Length 4: [0,1,2,3]
So total subarrays: 4 singles + 3 length2 + 2 length3 + 1 length4 = 10.
Now which have range exactly 2?
Range exactly 2:
[1,2]: diff2
[1,2,3]: diff2
[2,3]: diff1 -> no
[0,1]: diff3 no
[0,1,2]: diff3 no
[0,1,2,3]: diff3 no
Singles: diff0 no.
So exactly 2 subarrays: [1,2] and [1,2,3]. That's 2.
Now compute f(2) and f(1).
f(2): subarrays with range <=2:
Singles:4 (all)
[1,2]:2 -> yes
[2,3]:1 -> yes
[1,2,3]:2 -> yes
[0,1]:3 -> no
[0,1,2]:3 -> no
[0,1,2,3]:3 -> no
So total: 4 + 3 = 7? Wait, we have 4 singles, and three length2/3? Actually, we have [1,2], [2,3], [1,2,3] -> that's 3 more, total 7. But we also have length2 [0,1]? No, that's not. So 7.
But wait, we also have subarray of length 2: [0,1] is excluded, [1,2] included, [2,3] included. So that's 2 of length2? Actually, there are three length2 subarrays: [0,1], [1,2], [2,3]. So we include two of them. And length3: [0,1,2] excluded, [1,2,3] included. And length4: excluded. So total included: singles (4) + length2 (2) + length3 (1) = 7.
f(1): subarrays with range <=1:
Singles:4
[2,3]:1 -> yes
[1,2]:2 -> no
[1,2,3]:2 -> no
[0,1]:3 no
[0,1,2]:3 no
[0,1,2,3]:3 no
So only singles and [2,3]? That's 4+1=5.
But wait, is there any other? What about [3]? single already counted. So f(1)=5.
Then f(2)-f(1)=7-5=2. Correct.
So algorithm works.
Now, we need to implement carefully. But there is a potential inefficiency: In the while loop, we compute cur_max and cur_min by looking at the front of the deques. But what if the deques are empty? We set to nums[i]. That's fine.
But note: When we include nums[i], we update the deques. But in the condition check, we used cur_max and cur_min from the current window (without i). That's correct.
But what about the case where the current window is empty? Then we set cur_max = nums[i] and cur_min = nums[i]. Then new_max = nums[i], new_min = nums[i]. So condition holds. So we will include the first element always.
Now, one more thing: In the while loop, we might have a situation where after including some elements, the condition holds, but then we try to include the next and it fails. Then we break. That's fine.
But what about when we move left and the window shrinks? Then we might be able to include more on the right. So we do that in the next iteration.
So code seems correct.
But let's think about the count: We do count += right - left. That counts all subarrays starting at left and ending at any index from left to right-1. That is correct because for each such end, the window [left, end] is a subarray that satisfies condition? We need to ensure that every subarray [left, end] with end in [left, right-1] satisfies max-min <= L. But is that true? Since the window [left, right) (i.e., up to right-1) satisfies condition, and as we extend to the right, the range can only increase or stay the same? Actually, if we take a subarray that is a subset of the window [left, right), it will have range <= range of the whole window? Not necessarily: The range of a subarray is max-min over that subarray. If we take a smaller subarray, the max might be smaller and the min might be larger, so the range could be smaller. But could it be larger? No, because the max of a subarray cannot exceed the max of the larger set, and the min cannot be lower than the min of the larger set. So the range of any subarray contained in a set is at most the range of that set. Therefore, if the whole window [left, right) has range <= L, then every subarray within it also has range <= L. So indeed, for a fixed left, all subarrays starting at left and ending at any index from left to right-1 are valid. So counting right-left is correct.
But wait: What about subarrays that start at left and end at some index j where j < right-1? They are all contained in [left, right). So yes.
So the counting is correct.
Now, we need to implement count_at_most(L) as described.
But there is a common alternative: Instead of computing new_max and new_min hypothetically, we can simply try to add the element and then check condition, and if condition fails, we pop it from the deques? But that would be messy because we already added it. So our current method of computing new_max and new_min without actually adding is cleaner.
But we can also do: while right < n:
# add nums[right] to deques (temporarily)
# then check condition.
# if condition fails, then we need to remove the just added element from deques and break.
But that would require us to know how to remove it? We could store the indices we added? But it's simpler to compute hypothetically.
However, computing new_max and new_min by looking at current front is O(1). So it's fine.
But there is a catch: When we compute cur_max = nums[maxDeque[0]] if maxDeque else nums[i], but what if maxDeque is not empty but the index maxDeque[0] is not in the current window? We ensure that by popping from front when left moves. But at the beginning of the for loop for a given left, we have already removed the previous left. So the deques contain only indices in [left, right). So it's safe.
Now, let's code accordingly.
But wait: In the while loop, we are using the current deques which represent [left, right). Then we compute new_max and new_min. If condition holds, we add nums[i] to deques and increment right. If condition fails, we break without adding. That's correct.
Now, after we break, we count right-left. Note that right is the first index that we could not include. So the valid subarrays are those ending at indices left, left+1, ..., right-1. That's right-left many.
Then we remove left from deques if present. But note: The deques currently represent window [left, right). After we remove left, they represent [left+1, right). That is correct for the next iteration.
So the code is correct.
Now, we should test with edge cases: empty array? If nums is empty, then n=0. In count_at_most, for left in range(0) does nothing, returns 0. So answer 0. That's fine.
Single element: nums=[5], k=0: f(0)=1, f(-1)=0, answer=1. Correct. k=1: f(1)=1, f(0)=1, answer=0. Correct.
Now, what about k larger than possible range? For example, nums=[1,2,3], k=10. Then f(10) = all subarrays = 6, f(9)=6, answer=0. But actually, the maximum range is 2, so no subarray has range 10. So answer=0. That's correct.
What about k negative? As said, returns 0.
So we have a solution.
But is there any possibility of overflow? Count can be up to n*(n+1)/2, which for n up to 10^5 is about 5e9, fits in Python int.
Now, time complexity: O(n) for each count_at_most, so total O(n). But note that in the worst case, the while loop might run n times for each left? Actually, since right only increases, the total number of times the while loop body executes is at most n. Because right goes from 0 to n. So overall O(n). So two passes O(2n)=O(n).
So we are good.
Now, we need to write the function as requested: "Write a function that solves this problem". So we'll write a function that takes nums and k and returns the count.
We'll also explain the algorithm.
But before finalizing, let's consider an alternative approach: Using two pointers and two deques to count exactly k directly? That might be possible but more complicated. The difference method is simpler.
But wait: There is a subtle issue: The function count_at_most(L) as we implemented counts subarrays with range <= L. But is it correct for all L? We assumed that if the window [left, right) has range <= L, then any subarray within it also has range <= L. That is true. And we count all subarrays starting at left that end before right. But what about subarrays that start at left and end at right-1? That is included. But what about subarrays that start at left and end at an index j where j < right-1? They are also included because we count all from left to right-1. So that's fine.
But there is a nuance: When we move left, we remove left from deques. But what about subarrays that start at left and end at some index that is >= right? Those are not included because we break when we cannot include right. So for a fixed left, the maximum end index is right-1. So we count exactly those.
But is it possible that for a given left, there is a subarray [left, j] with j >= right that still satisfies condition? No, because we break when adding nums[right] would violate condition. But that means that for the window [left, right] (including right), the condition fails. But what about a subarray [left, j] with j > right? That would include nums[right] and more, so the range would be at least as large as the range of [left, right]? Not necessarily: adding more elements could increase the range or decrease? Actually, adding more elements can only increase the range or keep it the same? The range is max-min. Adding an element could increase the max or decrease the min, thus increasing the range. But it could also not change? But if [left, right] already has range > L, then any larger subarray containing that will have range at least as large? Not necessarily: Suppose [left, right] has max=10, min=1, range=9. If we add a very small element, min becomes smaller, range increases. If we add a very large element, max becomes larger, range increases. But could adding an element bring the max down? No, because max is the maximum, adding an element cannot decrease the max. Similarly, min cannot increase. So the range of a superset is at least the range of the subset. Therefore, if [left, right] has range > L, then any super set will also have range > L. So indeed, if we cannot include nums[right] because it would make the range > L, then we cannot include any further elements either because they would include nums[right] and more. So the maximum end index for a given left is exactly right-1. So our counting is correct.
Thus the method is sound.
Now, we must implement carefully in code.
One more thing: In the while loop, we compute new_max and new_min. But we can compute them more directly without using cur_max and cur_min? Actually, we can compute:
new_max = max(nums[i], maxDeque[0] if maxDeque else nums[i])
But that's what we did.
But what about when maxDeque is not empty but the element at maxDeque[0] might not be the maximum if we consider that the window might have multiple elements? Actually, it is the maximum. So it's fine.
But we can also do:
if maxDeque:
current_max = nums[maxDeque[0]]
else:
current_max = nums[i] # but wait, if empty, then current window is empty, so after adding nums[i], the max is nums[i]. But we are computing new_max = max(current_max, nums[i]). If empty, current_max should be something that doesn't affect? Actually, if window is empty, then the current max is undefined. But we want new_max = nums[i]. So we can set current_max to a very small number? But simpler: if maxDeque: current_max = nums[maxDeque[0]] else: current_max = nums[i]? That would give new_max = max(nums[i], nums[i]) = nums[i]. That's fine.
But careful: If maxDeque is empty, then current window is empty. So the maximum of the new window is nums[i]. So we can set current_max = nums[i]? Then new_max = max(nums[i], nums[i]) = nums[i]. That works. Similarly for min.
So we can do:
cur_max = nums[maxDeque[0]] if maxDeque else nums[i]
cur_min = nums[minDeque[0]] if minDeque else nums[i]
But that sets cur_max and cur_min to nums[i] when deques empty. Then new_max = max(cur_max, nums[i]) = nums[i], new_min = min(cur_min, nums[i]) = nums[i]. So condition holds.
But is that correct when deques are not empty? Yes.
So we can compute:
new_max = max(nums[i], nums[maxDeque[0]] if maxDeque else nums[i])
But that simplifies to: if maxDeque: new_max = max(nums[i], nums[maxDeque[0]]) else: new_max = nums[i].
Similarly for new_min.
But we can write:
if maxDeque:
candidate_max = nums[maxDeque[0]]
else:
candidate_max = nums[i]
new_max = max(candidate_max, nums[i])
But note: if maxDeque is not empty, candidate_max is the current max. Then new_max = max(candidate_max, nums[i]). That's correct.
Similarly for min.
So we can code:
while right < n:
i = right
if maxDeque:
current_max = nums[maxDeque[0]]
else:
current_max = nums[i]
if minDeque:
current_min = nums[minDeque[0]]
else:
current_min = nums[i]
new_max = max(current_max, nums[i])
new_min = min(current_min, nums[i])
if new_max - new_min <= L:
... include ...
else:
break
But we can combine:
if maxDeque:
new_max = max(nums[maxDeque[0]], nums[i])
else:
new_max = nums[i]
if minDeque:
new_min = min(nums[minDeque[0]], nums[i])
else:
new_min = nums[i]
That's equivalent.
Now, one more optimization: We can avoid computing new_max and new_min by checking condition using the deques after hypothetically adding? But it's fine.
Now, let's code accordingly.
But wait: In the inclusion step, we update the deques. But we use the same condition? Actually, we already checked condition, so we know it's safe to include. So we update deques.
But note: When we update the deques, we remove from the back elements that are <= for maxDeque? Actually, for maxDeque we maintain decreasing order? For sliding window maximum, we maintain a deque where the front is the maximum and the values are decreasing. So when adding a new element, we remove from the back all elements that are less than or equal to the new element? Actually, to maintain decreasing order, we remove from the back while the last element's value is less than or equal to the new element? Wait, if we want the front to be the maximum, we want the deque to be in decreasing order. So when we add a new element, we remove from the back all elements that are smaller than the new element because they will never become the maximum while the new element is in the window. But what about equal? If we have equal, we can remove the previous equal? Actually, if we have an element with the same value, we can remove the previous one because the new one is further to the right and will stay longer, so it's better to keep the newer one? But for the purpose of having the maximum, if they are equal, it doesn't matter which one we keep. But typically we remove while the last element is <= new element? That would remove all that are less or equal. But if we remove equal, then we lose the information that there is another element with that value? But if we have two equal maximums, we only need one of them? Actually, when the left pointer moves, we need to know if the element we are removing is the one at the front. If we remove the earlier equal, then when that index becomes left, we might not have it in the deque. But if we keep the later one, then when the earlier one leaves the window, it's already gone. So it's safe to remove earlier equals. So condition: while maxDeque and nums[maxDeque[-1]] <= nums[i]: pop. That gives a deque with strictly decreasing values? Possibly not strictly if we don't remove equals? But we remove equals, so after popping all <=, the remaining are > nums[i]. So the deque becomes strictly decreasing. That's fine.
Similarly for minDeque: we want increasing order? Actually, for minimum, we want the front to be the minimum. So we maintain a deque with increasing values. So when adding, we remove from the back while the last element's value is >= nums[i]. That gives strictly increasing? After removing all >=, the remaining are < nums[i]. So deque becomes strictly increasing.
But note: In the condition for minDeque, we use >=, so we remove equals as well. That's fine.
So our update code is:
while maxDeque and nums[maxDeque[-1]] <= nums[i]:
maxDeque.pop()
maxDeque.append(i)
while minDeque and nums[minDeque[-1]] >= nums[i]:
minDeque.pop()
minDeque.append(i)
That's standard.
Now, one more thing: In the removal step, we only remove if the front index equals left. That's correct because the element at left is leaving the window. If that element is the current maximum or minimum, it will be at the front of the respective deque. But it might not be at the front if there is a larger/smaller element after it? Actually, if the element at left is not the maximum, then it might not be at the front of maxDeque. But it could be somewhere in the deque? In a sliding window maximum deque, we only keep elements that are potentially maximum for future windows. So an element that is not the maximum might still be in the deque if it is larger than some elements after it? Actually, the deque stores indices in decreasing order of values. So if an element is not the maximum in the current window, it might still be in the deque if it is larger than some elements to its right? But when we remove from the back during addition, we remove elements that are smaller than the new one. So the deque contains indices of elements that are decreasing in value. So the front is the maximum. But an element that is not the maximum might be in the deque if it is the second largest, etc. But when that element leaves the window (i.e., its index equals left), we need to remove it from the deque. But it might not be at the front. So we cannot simply check if the front equals left. We need to remove it from wherever it is. But in the standard sliding window maximum algorithm, we remove from the front only when the index is out of the window (i.e., less than left). But here we are moving left one by one, so we remove the element at index left. That element might be anywhere in the deque. But we don't know its position. So we cannot efficiently remove it from the middle without scanning. That's a problem.
Ah! I made a mistake. In the standard two-pointer for "at most" condition, we usually maintain the deques for the current window, and when we move left forward, we remove the element at left from the deques only if it is at the front. But is that sufficient? Let's think: In the sliding window maximum problem, we have a fixed window size. But here the window is variable and we are moving left and right. When we move left forward by one, the element at index left leaves the window. If that element is the current maximum, then it must be at the front of the maxDeque? Actually, in the maxDeque, the indices are stored in decreasing order of values. The front is the index of the maximum value in the window. But if the element at left is not the maximum, then its value is less than the maximum. Could it still be in the deque? Yes, because it might be larger than some elements that come after it, so it could be in the deque as a candidate for maximum after the current maximum leaves. But when we move left, that element leaves the window. We need to remove it from the deque if it is present. But we don't know where it is. However, in the standard sliding window maximum algorithm, we only remove from the front when the index is out of the window (i.e., when the index at the front is less than the current left). But here, we are moving left forward one by one, so we can check: if the front of the deque is equal to left, then it means that element is leaving and it is the current maximum? Not necessarily: It could be that the front is the maximum, and if that maximum is at index left, then we pop it. But what if the element at left is not the maximum? Then it might not be at the front. But it could be somewhere else in the deque. Do we need to remove it? Yes, because it is no longer in the window. But if we don't remove it, then when we later check the front, it might be an index that is less than left? Actually, we are moving left forward, so indices less than left are out of the window. In the standard algorithm, we remove from the front only when the index at the front is less than the current left. But here, we are incrementing left by one each time. So at the beginning of the loop for a given left, the deques should contain only indices >= left. But we are about to remove left. So after we remove left, the deques should contain indices >= left+1. So we need to remove left from the deques if it is present. But we can do it by checking if the front is left? That only removes it if it is at the front. But if it is not at the front, then it is somewhere in the middle. However, in the maxDeque, the indices are stored in decreasing order of values, but also the indices themselves are increasing? Actually, when we add indices, we add them in order of increasing index. But we remove from the back based on values. So the indices in the deque are not necessarily in increasing order? Let's see: We process indices from left to right. When we add an index i, we remove from the back indices that have values <= nums[i]. But we do not remove based on index. So the indices in the deque are in increasing order? Since we add i, and we only remove from the back, the remaining indices in the deque are in increasing order? Consider: We start with empty. Add index 0. Then add index 1: if nums[1] > nums[0], we remove 0 and then add 1. So deque has [1]. If nums[1] <= nums[0], we keep 0 and add 1, so deque becomes [0,1]. So indices are increasing. In general, since we only remove from the back, the indices in the deque are in increasing order from front to back. That is because we never remove an index that is earlier than a later index? Actually, if we have indices i and j with i<j, and we add j, we might remove i if nums[i] <= nums[j]. But if we don't remove i, then i remains and j is appended, so i<j. So the deque always has indices in increasing order. So the front has the smallest index? Not necessarily: the front is the maximum value, but its index could be anywhere. However, the indices are in increasing order because we only append at the back and only remove from the back or front. So the deque stores indices in increasing order from front to back. That is a property of the sliding window maximum deque: the indices are in increasing order, and the values are decreasing. So the front has the smallest index among the candidates? Not necessarily: the front has the maximum value, but its index could be any. However, since indices are in increasing order, the front index is the smallest index in the deque? Not necessarily: if we have [0,1] with values [10,5], then front is 0, which is smallest. But if we have [0,1] with values [5,10], that cannot happen because when we added 1, we would have removed 0 since 5<=10? Actually, condition: while deque and nums[deque[-1]] <= nums[i]: pop. So if nums[0]=5, nums[1]=10, then when adding 1, we see last element value 5 <=10, so we pop 0. Then deque becomes [1]. So we cannot have a situation where a later index has a larger value and an earlier index remains. So the deque is such that values are strictly decreasing from front to back. And since we only append at the back, indices are increasing. So the front index is the oldest index among the candidates? Not necessarily oldest, but it is the index of the maximum value. And since indices are increasing, the front index is the smallest index in the deque? Because if there is an index smaller than the front, it would have been removed earlier? Actually, consider: we add index 0 -> deque [0]. Add index 1 with value less than nums[0]: then we keep both, so deque [0,1]. Here front index 0 is smaller than 1. So front index is the smallest index in the deque. Is that always true? Suppose we have indices: 0:10, 1:5, 2:8. Process:
0: deque [0]
1: nums[1]=5, last element 10>5, so we append: deque [0,1]
2: nums[2]=8. Compare with last: nums[1]=5 <=8, so pop 1. Now deque [0]. Compare with last: nums[0]=10>8, so append 2. Deque [0,2]. Front index 0 is smaller than 2. So yes, the front index is the smallest index in the deque. Because when we add a new index, we remove from the back indices that have smaller or equal values, but we never remove an index that has a larger value. So the indices that remain are those that have not been removed by a later larger element. And since we only remove from the back, the indices that remain are in increasing order. And the front is the one with the largest value, but its index might not be the smallest? Actually, from the examples, it seems the front index is the smallest. Let's prove: Suppose we have two indices i and j in the deque with i<j. Then when j was added, i was not removed because nums[i] > nums[j]? Actually, we remove from the back while the last element's value <= nums[j]. So if i is before j and i is still in the deque when j is added, then at the moment of adding j, the last element in the deque is some index k. If i is not the last, then there might be others between. But eventually, for i to remain, when j was added, we must have that nums[i] > nums[j]? Not necessarily: i might not have been the last at that time. But if i is in the deque and i<j, then when j was added, we removed from the back all elements with value <= nums[j]. If nums[i] <= nums[j], then i would have been removed at that time if it was at the back? But i might not be at the back if there are other indices after i. However, since we remove from the back consecutively, if there is any index after i with value <= nums[j], it will be removed. But i itself might not be at the back. So it's possible that i remains even if nums[i] <= nums[j]? Let's construct: indices: 0:10, 1:5, 2:8, 3:6. Let's simulate:
0: deque [0]
1: nums[1]=5, last=10>5, append -> [0,1]
2: nums[2]=8, compare with last: nums[1]=5 <=8, pop 1 -> [0]; compare with last: nums[0]=10>8, append -> [0,2]
3: nums[3]=6, compare with last: nums[2]=8>6, append -> [0,2,3]
Now we have indices 0,2,3. The front index is 0, which is smallest. But what about index 2 and 3? They are after 0. So the front is always the smallest index? In this deque, indices are increasing: 0,2,3. So front is smallest. Is it possible to have a deque where the front index is not the smallest? Suppose we have indices: 0:5, 1:10, 2:8. Process:
0: [0]
1: nums[1]=10, last=5<=10, pop 0 -> [1]
2: nums[2]=8, last=10>8, append -> [1,2]
Here front is 1, which is not the smallest index? The smallest index in the deque is 1, but there is index 0 that is not in the deque. So among the indices present, front is the smallest? In [1,2], front=1 is smaller than 2. So yes, the deque stores indices in increasing order. That's a property: since we only append at the back and only remove from the back or front, and we never insert in the middle, the indices in the deque are in increasing order from front to back. So the front index is the smallest index in the deque. Therefore, when we move left forward, if the element at index left is in the deque, it must be at the front? Because if it's in the deque, its index is left, and since indices in deque are increasing, the front has the smallest index. So if left is in the deque, then the front index must be left? Not necessarily: what if there is an index smaller than left still in the deque? But we have been removing lefts from the front in previous iterations. At the beginning of the loop for a given left, the deques should contain only indices >= left. But we haven't removed left yet. So the smallest index in the deque is at least left. If left is present, then it is the smallest index, so it must be at the front. Therefore, we can check if the front index equals left to remove it. That is correct.
Similarly for minDeque: the indices are in increasing order? For minDeque, we maintain increasing values? Actually, for minDeque, we maintain increasing values from front to back? Let's see: We remove from the back while last value >= nums[i]. So after adding, the values are increasing? Suppose we have values: front smallest, back largest? Actually, we want the front to be the minimum. So we maintain a deque where values are non-decreasing from front to back? Let's simulate: For minDeque, we want the front to be the smallest. When we add a new element, we remove from the back all elements that are greater than or equal to the new element. So after that, the last element is less than the new element. So the values in the deque are strictly increasing from front to back? Example: values: 5,3,4.
0:5 -> deque [0]
1:3 -> remove last? nums[0]=5 >=3, so pop 0. Then deque [1].
2:4 -> compare with last: nums[1]=3 <4, so append -> [1,2]. Values: 3,4 increasing.
Another example: 3,1,2.
0:3 -> [0]
1:1 -> nums[0]=3>=1, pop -> [1]
2:2 -> nums[1]=1<2, append -> [1,2]. Values 1,2 increasing.
So yes, the values in the minDeque are strictly increasing from front to back. And indices are also increasing because we append in order. So the front index is the smallest index. Therefore, when we remove left, we only need to check if the front index equals left.
So our removal by checking front is correct.
Thus the algorithm is correct.
Now, we need to write the code accordingly.
But wait: In the while loop, we compute new_max and new_min using current front values. But what if the current window is empty? Then maxDeque is empty, we set cur_max = nums[i]? But then new_max = max(nums[i], nums[i]) = nums[i]. That's fine. But we also set cur_min similarly. So condition holds. But then we add nums[i] to deques. That's correct.
But what about when the window is not empty? We use the front values. That's correct.
Now, let's write the final code.
We'll define:
from collections import deque
def count_at_most(nums, L):
n = len(nums)
if L < 0:
return 0
maxDeque = deque()
minDeque = deque()
left = 0
right = 0
count = 0
for left in range(n):
while right < n:
i = right
# compute potential new max and min after including i
if maxDeque:
cur_max = nums[maxDeque[0]]
else:
cur_max = nums[i]
if minDeque:
cur_min = nums[minDeque[0]]
else:
cur_min = nums[i]
new_max = max(cur_max, nums[i])
new_min = min(cur_min, nums[i])
if new_max - new_min <= L:
# include i
while maxDeque and nums[maxDeque[-1]] <= nums[i]:
maxDeque.pop()
maxDeque.append(i)
while minDeque and nums[minDeque[-1]] >= nums[i]:
minDeque.pop()
minDeque.append(i)
right += 1
else:
break
count += right - left
# remove left from deques if they are at the front
if maxDeque and maxDeque[0] == left:
maxDeque.popleft()
if minDeque and minDeque[0] == left:
minDeque.popleft()
return count
def subarray_range(nums, k):
return count_at_most(nums, k) - count_at_most(nums, k-1)
But we can optimize: Instead of computing cur_max and cur_min separately, we can compute directly:
new_max = nums[i]
if maxDeque:
new_max = max(new_max, nums[maxDeque[0]])
new_min = nums[i]
if minDeque:
new_min = min(new_min, nums[minDeque[0]])
That's simpler.
So:
while right < n:
i = right
new_max = nums[i]
new_min = nums[i]
if maxDeque:
new_max = max(new_max, nums[maxDeque[0]])
if minDeque:
new_min = min(new_min, nums[minDeque[0]])
if new_max - new_min <= L:
... update deques ...
right += 1
else:
break
That is cleaner.
Now, test with the example nums=[1,2], L=1: works.
Now, one more test: nums=[3,1,2], L=1? Let's manually compute f(1):
Subarrays:
[3]:0
[1]:0
[2]:0
[3,1]:2 -> no
[1,2]:1 -> yes
[3,1,2]:2 -> no
So f(1)=4? Actually, singles 3 and [1,2] -> 4.
Now simulate algorithm:
n=3.
left=0, right=0.
while: i=0, new_max=3, new_min=3, diff=0<=1 -> include.
update: maxDeque: empty -> append0 -> [0]; minDeque: append0 -> [0]; right=1.
while: i=1, new_max = max(3,1)=3, new_min = min(3,1)=1, diff=2>1 -> break.
count += right-left =1-0=1.
remove left=0: maxDeque[0]==0 -> pop -> []; minDeque[0]==0 -> pop -> [].
left=1:
while: i=1, new_max=1, new_min=1, diff=0<=1 -> include.
maxDeque: append1 -> [1]; minDeque: append1 -> [1]; right=2.
while: i=2, new_max = max(1,2)=2, new_min = min(1,2)=1, diff=1<=1 -> include.
update maxDeque: last element value 1<=2? yes, pop. then append2 -> [2].
minDeque: last element value 1>=2? false, so append -> [1,2].
right=3.
while: right==3, break.
count += right-left =3-1=2.
remove left=1: maxDeque[0]==1? no, maxDeque[0]==2. minDeque[0]==1 -> pop -> minDeque becomes [2].
left=2:
while: right=3, so skip.
count += right-left =3-2=1.
remove left=2: maxDeque[0]==2 -> pop -> []; minDeque[0]==2 -> pop -> [].
total count =1+2+1=4. Correct.
So f(1)=4. f(0) should be 3 (singles). Let's test f(0):
left=0:
i=0: include, right=1.
i=1: new_max = max(3,1)=3, new_min=min(3,1)=1, diff=2>0 -> break. count=1, remove0.
left=1:
i=1: include, right=2.
i=2: new_max = max(1,2)=2, new_min=min(1,2)=1, diff=1>0 -> break. count += right-left =2-1=1 -> total=2.
remove left=1: maxDeque[0]==1? after including 1 and then breaking? Actually, after including 1, maxDeque=[1], minDeque=[1]. Then we break. So at removal, maxDeque[0]==1, pop. minDeque[0]==1, pop.
left=2:
i=2: include, right=3. count +=3-2=1 -> total=3.
remove left=2: pop.
So f(0)=3. Difference for k=1: 4-3=1. But wait, we expected exactly k=1 to be 1? From above, only [1,2] has range1. So that's correct.
But in the example nums=[3,1,2], k=1, we have one subarray. So f(1)-f(0)=4-3=1. Correct.
So algorithm works.
Now, what about a case where the window might have multiple elements and the max/min change not at the ends? It should be fine.
Now, we should consider the possibility of integer overflow? In Python, no.
Now, we need to explain the algorithm in the response. The user asked: "You are given an array of integers nums. Write a function to find the number of subarrays that have a range (max - min) equal to a given value k. Please write a function that solves this problem, and explain your algorithm."
So we will provide:
- Explanation: We use the technique of counting subarrays with range at most L and then subtract to get exactly k.
- To count subarrays with range at most L, we use a sliding window with two deques to maintain the maximum and minimum in the current window. We expand the right pointer as far as possible for each left, and count the subarrays starting at left.
- Complexity: O(n) time and O(n) space.
We'll write the code accordingly.
But wait: There is an alternative method: Directly counting exactly k using two pointers and two deques? That might be more efficient in terms of constant factors? But the difference method is fine.
However, note that count_at_most is called twice. That means we are doing two passes over the array. But we can combine them into one pass? Possibly by computing both counts simultaneously? But that would be more complex. Two passes O(2n) is still O(n). So it's acceptable.
But we must be cautious: The two calls are independent, so we are essentially running the same algorithm twice. That's fine.
Now, let's consider if k can be very large? Then count_at_most(k) will count all subarrays, which is n*(n+1)/2. That's fine.
Now, we need to handle the case where k is negative? As discussed, we can return 0 if k<0. But our count_at_most for negative L returns 0. So difference will be 0. So we don't need special case, but it's fine.
But what if k-1 is negative? That's fine.
Now, one more edge: What if the array has duplicate values? Our deques handle duplicates? For maxDeque, we remove while <=, so if we have duplicates, we remove the previous one when a new one comes. That means we keep only the last occurrence of that value? Actually, if we have equal values, we remove the previous one. That is fine because the new one is further to the right and will stay longer, so it's sufficient. For example, nums=[2,2], L=0. For left=0: include index0, then try index1: new_max = max(2,2)=2, new_min=min(2,2)=2, diff=0<=0 -> include. But when including index1, for maxDeque: we have [0] with value2. Since nums[1]=2, we check while last element value <=2 -> 2<=2 true, so pop0. Then append1. So maxDeque becomes [1]. Similarly minDeque: we remove while >= -> 2>=2 true, pop0, append1. So after including both, maxDeque and minDeque have [1]. Then when we move left to 1, we remove left=0? But left is still 0? Actually, after counting for left=0, we remove left=0. But at that time, maxDeque front is 1, not 0. So we don't pop. That's fine because index0 is not in the deques. But wait, we included index1, so the window for left=0 is [0,2) i.e., indices 0 and 1. But our deques after including both have only index1. That means the maximum is at index1, but index0 is also in the window. But we removed index0 from the deques because it was equal to the new value. That's okay because index1 has the same value, so the maximum is still correct. But when we later move left to 1, the window becomes [1,2). We need to remove index0 from the window. But index0 is not in the deques, so we don't need to remove it. That's fine. However, is it correct that index0 is not in the deques? The window [0,1] has two elements both 2. The maximum is 2. The deque for max should contain the index of the maximum. Since both are maximum, it doesn't matter which one we keep. We kept the later one. That's fine because when the left pointer moves to 1, the window becomes [1,2) which includes only index1. The maximum should be at index1. And our deque has [1]. So it's correct.
But what about the count? For left=0, we count right-left. After including both, right=2. So count += 2-0 =2. That counts subarrays [0] and [0,1]. That's correct. Then for left=1, we have right=2, so count += 2-1=1, counting [1]. Total 3. That's all subarrays. For L=0, we want only subarrays with all equal? Actually, for L=0, we want subarrays where max-min<=0, i.e., all elements equal. In [2,2], all subarrays have all elements equal? [0]:2, [1]:2, [0,1]: both 2. So all 3 subarrays have range 0. So f(0)=3. That matches.
So duplicates are handled.
Now, what about a case where the window shrinks and the front of the deque is not left? We argued that if left is in the deque, it must be at the front because indices are increasing. But what if left is not in the deque? Then we don't remove anything. That's fine.
But is it always true that if an index is in the deque, then it is the smallest index? Yes, because the deque stores indices in increasing order. So the front is the smallest index. Therefore, when we move left forward, if the element at left is still in the window, it must be the smallest index in the deque? Not necessarily: there could be an index smaller than left still in the deque? But we have been removing lefts from the front in previous iterations. At the beginning of the loop for a given left, the deques contain only indices >= left. So the smallest index in the deque is at least left. If left is present, then it is the smallest index, so it must be at the front. Therefore, checking maxDeque[0] == left is sufficient to remove it.
But what about if left is not present? Then we don't remove. That's fine.
So the removal is correct.
Now, we should test with a case where the element at left is not the maximum but is in the deque. For example, nums=[5,3,1,2,4], L= something. But according to our property, if an index is in the deque, it must be that there is no later index with a value greater than or equal to it? Actually, for maxDeque, we remove from the back while nums[back] <= nums[i]. So if an index j is in the deque, then for any k>j that was added after j, if nums[k] >= nums[j], then j would have been removed when k was added. Therefore, for any index j in the deque, all indices after j have values less than nums[j]? Not exactly: they have values less than nums[j]? Actually, if there is a k>j with nums[k] >= nums[j], then when k was added, we would have removed j because j would be at the back? Not necessarily: j might not be at the back at that time. But consider: when we add k, we remove from the back consecutively until the last element has value > nums[k]. So if j is in the deque and there is a k>j with nums[k] >= nums[j], then when k was added, we would have removed from the back all elements with value <= nums[k]. Since nums[k] >= nums[j], j would be removed if it was at the back. But what if j is not at the back because there are other indices between j and k that have values > nums[j]? Then j might survive. Example: nums: j=0:10, then index1:15, index2:12. Process:
0: deque [0]
1: nums[1]=15, last=10<=15, pop0, then deque [1]
2: nums[2]=12, last=15>12, so append -> [1,2]
Now j=0 is gone. What about an index that is not the maximum? Suppose: 0:10, 1:5, 2:8. We already did: after 2, deque [0,2]. Here index0 is in the deque and it is not the maximum? Actually, index0 has value10, index2 has value8. So index0 is the maximum. So it's the maximum. Can we have a situation where an index that is not the maximum is in the deque? Suppose: 0:5, 1:10, 2:8. After 0: [0]. After 1: remove0, [1]. After 2: append -> [1,2]. Here index2 has value8, which is less than 10, so it's not the maximum. But it is in the deque. And its index is 2. When left moves to 0, we remove left=0. But 0 is not in the deque. When left moves to 1, we need to remove index1? At that time, deque has [1,2]. Front is 1, so we remove it because left=1. Then deque becomes [2]. That's correct. So index2 remains. So indeed, an index that is not the maximum can be in the deque. But its index is greater than the front index? In [1,2], front is 1, which is smaller than 2. So the front index is the smallest index in the deque. So if left is equal to some index that is in the deque but not the front, that would contradict because the front is the smallest index. So if left is in the deque, it must be the smallest index, hence the front. Therefore, our removal by checking front is sufficient.
But what about minDeque? Similarly, the indices in minDeque are increasing, and the front is the smallest index. So if left is in the minDeque, it must be at the front.
Thus the removal is correct.
Now, we should also consider that after we break out of the while loop, we count right-left. But right might be equal to left? That's fine, count 0.
Now, what about when L is very small, such that even single elements might not satisfy? But single elements have range 0, so if L>=0, they always satisfy. If L<0, then no element satisfies, and we return 0. So that's fine.
Now, let's write the final code.
But wait: In the while loop, we compute new_max and new_min using the current front values. But what if the current window is empty? Then we set new_max and new_min to nums[i]? Actually, if maxDeque is empty, we set new_max = nums[i]? But then we also have new_min similarly. That's fine.
But what if maxDeque is not empty but minDeque is empty? That cannot happen because we always add to both deques together? Actually, we add to both when we include an element. So if maxDeque is not empty, minDeque should also not be empty? Not necessarily: we might have added elements only to maxDeque? No, we add to both when we include. So at any time, both deques have the same set of indices? Not exactly: they may have different indices because we remove from the back based on different conditions. But they both contain indices that are in the current window. However, it is possible that one deque is empty while the other is not? Consider a window with one element: both deques have that index. When we add a second element that is larger, for maxDeque we remove the first because smaller, so maxDeque has only the new index. For minDeque, we keep the first because it is smaller? Actually, if second is larger, for minDeque we check: last element value >= nums[i]? If first is smaller, then we don't remove, so minDeque has both indices. So after including two elements, maxDeque might have only the second index, minDeque has both. So minDeque is not empty. Similarly, if second is smaller, then for maxDeque we keep both? Actually, if second is smaller, for maxDeque: last element value <= nums[i]? If first is larger, then we don't remove, so maxDeque has both. For minDeque: we remove first because it is larger? Actually, if second is smaller, then for minDeque: while last value >= nums[i]? The last is first, value > nums[i]? If first is larger, then we remove it, so minDeque has only second. So in all cases, after including at least one element, both deques are non-empty? Not necessarily: if we have a window with one element, both have it. When we add a second element, depending on values, one deque might become empty? Let's see: maxDeque: we remove from back while <= new. If the existing element is <= new, we remove it. If it is > new, we keep it. So after adding, maxDeque will have at least the new index. So it will not be empty. Similarly for minDeque: we remove from back while >= new. If the existing element is >= new, we remove it. If it is < new, we keep it. So after adding, minDeque will have at least the new index. So both deques will have at least the new index. Therefore, after we have included at least one element, both deques are non-empty. So in the while loop, when right>left, both deques are non-empty. But initially, when right==left and we are about to include the first element, both are empty. So our handling of empty case is needed only for the first element. After that, both deques will be non-empty. So in the condition check, we can simplify: if maxDeque is empty, then it means the window is empty. But after we have included at least one element, maxDeque won't be empty. But when we move left and remove the last element? Consider a window that becomes empty? Actually, after we remove left, if left was the only element, then both deques become empty. Then for the next left, the window might be empty? But in the for loop, left increments, and we start with the same right. But if right == left, then the window is empty. So we need to handle empty deques. So our code is fine.
Now, we should test with a case where after moving left, the window becomes empty and then we try to extend right. For example, nums=[1,2], L=1. After left=0, we had window [0,2) with two elements. Then we remove left=0 from deques? But after including both, maxDeque had [1] and minDeque had [0,1]? Actually, after including both, maxDeque=[1], minDeque=[0,1]. Then we count for left=0: count +=2. Then we remove left=0: maxDeque[0]==0? no, so not removed. minDeque[0]==0, so pop -> minDeque becomes [1]. Then left becomes 1. Now window is [1,2) i.e., index1 only. Deques: maxDeque=[1], minDeque=[1]. So non-empty. So no empty window.
But what about when we have a single element and then we move left past it? Example: nums=[1], L=0. left=0: include index0, right=1. count +=1. remove left=0: both deques have 0, so pop. Then deques empty. Then left increments to 1, but for loop ends because left in range(1) only? n=1, so for left in range(1) gives left=0 only. So we never have left=1. So no issue.
But consider nums=[1,2], and suppose L=0. Then for left=0: we include index0, then try index1: new_max=max(1,2)=2, new_min=min(1,2)=1, diff=1>0 -> break. So right remains 1. count +=1-0=1. Then remove left=0: both deques have 0? After including index0, maxDeque=[0], minDeque=[0]. So we pop both. Then left=1: while right<2: right=1, i=1. deques empty, so new_max=2, new_min=2, diff=0<=0 -> include. Then right=2. count +=2-1=1. Then remove left=1: pop. So total count=2. That's correct.
So empty deques can occur when the window is empty, which happens when right==left. So our code handles that.
Now, we should think about performance: In the worst case, each element is added and removed from each deque at most once. So O(n) per call.
Now, we need to write the explanation.
But there is an alternative approach: Using two pointers and maintaining the max and min with heaps? That would be O(n log n). Our O(n) is better.
So we'll go with this.
Now, we must write the function as asked. The function signature: probably something like:
def count_subarrays(nums, k):
...
We'll implement that.
Now, one more nuance: The problem says "range (max - min) equal to a given value k". So k can be zero. That's fine.
Now, let's code.
But before finalizing, let's test with a larger example to be sure.
Example: nums = [1,3,2,4,5], k=3.
We want exactly range=3.
List subarrays with range exactly 3:
Compute all subarrays and their ranges:
Singles: range0.
Length2:
[1,3]:2
[3,2]:1
[2,4]:2
[4,5]:1
Length3:
[1,3,2]: max3 min1 diff2
[3,2,4]: max4 min2 diff2
[2,4,5]: max5 min2 diff3 -> exactly 3? 5-2=3, yes.
Length4:
[1,3,2,4]: max4 min1 diff3 -> exactly3.
[3,2,4,5]: max5 min2 diff3 -> exactly3.
Length5:
[1,3,2,4,5]: max5 min1 diff4.
So exactly3: [2,4,5], [1,3,2,4], [3,2,4,5] -> 3 subarrays.
Now compute f(3) and f(2).
f(3): subarrays with range <=3.
We need to list all subarrays with range <=3.
Singles:5
Length2: all? [1,3]:2<=3, [3,2]:1, [2,4]:2, [4,5]:1 -> all 4.
Length3: [1,3,2]:2<=3, [3,2,4]:2<=3, [2,4,5]:3<=3 -> all 3.
Length4: [1,3,2,4]:3<=3, [3,2,4,5]:3<=3 -> both 2.
Length5: [1,3,2,4,5]:4>3 -> no.
Total: 5+4+3+2=14.
But total subarrays = 5*6/2=15. So f(3)=14.
f(2): subarrays with range <=2.
Singles:5
Length2: [1,3]:2 yes, [3,2]:1 yes, [2,4]:2 yes, [4,5]:1 yes -> all4.
Length3: [1,3,2]:2 yes, [3,2,4]:2 yes, [2,4,5]:3 no -> so 2.
Length4: [1,3,2,4]:3 no, [3,2,4,5]:3 no -> 0.
Length5: no.
Total: 5+4+2=11.
Difference: 14-11=3. Correct.
So algorithm works.
Now, we need to write code.
But wait: In the while loop, we are checking new_max - new_min <= L. But what about when L is very large? That's fine.
Now, we should also consider that the array might have negative numbers? Our algorithm doesn't assume positive, so it's fine.
Now, let's write the final code with proper function.
We'll write:
from collections import deque
def count_subarrays_with_range_at_most(nums, L):
n = len(nums)
if L < 0:
return 0
maxDeque = deque()
minDeque = deque()
right = 0
count = 0
for left in range(n):
# Expand the window as far as possible from the current right
while right < n:
i = right
new_max = nums[i]
new_min = nums[i]
if maxDeque:
new_max = max(new_max, nums[maxDeque[0]])
if minDeque:
new_min = min(new_min, nums[minDeque[0]])
if new_max - new_min <= L:
# Add nums[i] to the deques
while maxDeque and nums[maxDeque[-1]] <= nums[i]:
maxDeque.pop()
maxDeque.append(i)
while minDeque and nums[minDeque[-1]] >= nums[i]:
minDeque.pop()
minDeque.append(i)
right += 1
else:
break
count += right - left
# Remove the left element from the deques if it is at the front
if maxDeque and maxDeque[0] == left:
maxDeque.popleft()
if minDeque and minDeque[0] == left:
minDeque.popleft()
return count
def subarray_range(nums, k):
return count_subarrays_with_range_at_most(nums, k) - count_subarrays_with_range_at_most(nums, k-1)
That should be it.
But let's test with the example nums=[1,3,2,4,5], k=3 to see if we get 3.
We can simulate quickly but it's long. But we trust.
Now, we need to provide explanation.
Explanation:
We want to count subarrays where max - min = k. Instead of counting exactly, we count subarrays with range <= k and subtract those with range <= k-1. This works because a subarray has range exactly k iff it has range <= k but not <= k-1.
To count subarrays with range <= L, we use a sliding window with two pointers (left and right) and two deques to maintain the maximum and minimum in the current window [left, right). For each left, we expand right as far as possible such that the window [left, right) has range <= L. Then, all subarrays starting at left and ending at any index from left to right-1 satisfy the condition, so we add (right - left) to the count. Then we move left forward by one, removing the element at left from the deques if it is at the front (since deques store indices in increasing order, the leftmost element is at the front). We continue until left reaches the end.
The deques are maintained as follows:
- maxDeque: indices of elements in decreasing order of value, so the front is the index of the maximum.
- minDeque: indices of elements in increasing order of value, so the front is the index of the minimum.
When adding a new element at index i, we remove from the back of maxDeque all indices with value <= nums[i] and then append i. Similarly, we remove from the back of minDeque all indices with value >= nums[i] and then append i.
The window expansion checks if including nums[right] would keep the range <= L by comparing the potential new maximum (max of current maximum and nums[right]) and potential new minimum (min of current minimum and nums[right]). If the condition holds, we include nums[right] and update the deques; otherwise, we stop.
The overall time complexity is O(n) because each element is added to and removed from each deque at most once, and the pointers left and right each move at most n steps. The space complexity is O(n) for the deques (in the worst case, they might store all indices).
Thus, the total time is O(n) for each call to count_at_most, and we call it twice, so O(n) overall.
Now, we output the code.
But wait: The problem statement says "Write a function to find the number of subarrays that have a range (max - min) equal to a given value k." So we need to write a function that takes nums and k and returns an integer.
We'll define:
def count_subarrays(nums, k):
# as above
But we named it subarray_range. We should name it appropriately. Let's call it count_subarrays_with_range.
But the user said "Write a function", so we can name it as we like. We'll use:
def count_subarrays(nums, k):
But to avoid confusion, we'll use:
def subarray_range(nums, k): # as above
But the name "subarray_range" might be interpreted as something else. We'll use "count_subarrays" or "num_subarrays".
Let's use:
def count_subarrays(nums, k):
return count_at_most(nums, k) - count_at_most(nums, k-1)
And define count_at_most as a helper.
We'll put it all together.
Now, we need to output the code and explanation.
But the user said "Please write a function that solves this problem, and explain your algorithm." So we should provide both.
In the response, we'll give an explanation and then the code.
Now, I'll write the final answer.
To solve this problem, we need to count the number of contiguous subarrays in an array nums where the range (difference between the maximum and minimum elements) is exactly equal to a given value k.
Approach
The key insight is to transform the problem of counting subarrays with exactly range k into counting subarrays with range at most k and subtracting those with range at most k-1. This works because a subarray has range exactly k if and only if its range is ≤ k but not ≤ k-1.
Counting subarrays with range ≤ L
We use a sliding window technique with two pointers (left and right) and two monotonic deques:
- maxDeque: Maintains indices of elements in decreasing order. The front always holds the index of the current maximum in the window
[left, right).
- minDeque: Maintains indices of elements in increasing order. The front always holds the index of the current minimum.
For each left from 0 to n-1:
- Expand
right as far as possible such that the window [left, right) has range ≤ L. For each candidate right, we compute the potential new maximum and minimum if nums[right] were included (by comparing nums[right] with the current max and min from the deques). If the new range ≤ L, we add right to the deques (removing smaller/larger elements from the back to maintain monotonicity) and increment right.
- Count subarrays: All subarrays starting at
left and ending at any index from left to right-1 are valid because any subarray within a valid window also has range ≤ L. So we add right - left to the total count.
- Shrink the window: Before moving
left forward, remove left from the deques if it is at the front (since deques store indices in increasing order, left can only be at the front if present).
This sliding window ensures each element is processed at most twice (once when added, once when removed), giving an O(n) time complexity.
Final Count
The answer is count_at_most(k) - count_at_most(k-1).
Complexity
- Time: O(n) for each call to
count_at_most, and we call it twice → O(n) overall.
- Space: O(n) for the deques (worst-case they store all indices).
Solution Code
from collections import deque
def count_at_most(nums, L):
n = len(nums)
if L < 0:
return 0
maxDeque = deque()
minDeque = deque()
right = 0
count = 0
for left in range(n):
while right < n:
i = right
new_max = nums[i]
new_min = nums[i]
if maxDeque:
new_max = max(new_max, nums[maxDeque[0]])
if minDeque:
new_min = min(new_min, nums[minDeque[0]])
if new_max - new_min <= L:
while maxDeque and nums[maxDeque[-1]] <= nums[i]:
maxDeque.pop()
maxDeque.append(i)
while minDeque and nums[minDeque[-1]] >= nums[i]:
minDeque.pop()
minDeque.append(i)
right += 1
else:
break
count += right - left
if maxDeque and maxDeque[0] == left:
maxDeque.popleft()
if minDeque and minDeque[0] == left:
minDeque.popleft()
return count
def count_subarrays(nums, k):
return count_at_most(nums, k) - count_at_most(nums, k-1)
Explanation
- count_at_most(nums, L): Counts subarrays with range ≤
L using a sliding window. It expands right while the window remains valid (range ≤ L), counts all valid subarrays starting at left, then shrinks from the left.
- count_subarrays(nums, k): Returns the difference between subarrays with range ≤
k and those with range ≤ k-1, yielding exactly those with range k.
This approach efficiently narrows down the exact count by leveraging monotonic deques for O(1) max/min queries within the sliding window.