You are given an array of integers nums. Write a function to find the number of subarrays that have a sum of absolute differences between adjacent elements equal to a given value k. Please write a function that solves this problem, and explain your algorithm.
Assistant
We need to count subarrays where the sum of absolute differences between adjacent elements equals k. That is, for a subarray nums[i..j] (i <= j), we define:
If the subarray length is 1, there are no adjacent pairs, so sum of absolute differences is 0? Actually adjacent differences defined for pairs of consecutive elements. For a subarray of length 1, there are no adjacent elements, so sum is 0. Should we count those when k=0? Possibly. But we need to clarify: "sum of absolute differences between adjacent elements" means for subarray from index i to j (inclusive), we sum |nums[t] - nums[t+1]| for t from i to j-1. So it's defined only for length >= 2. For length 1, the sum is 0 (since no terms). Many definitions consider empty sum as 0. So subarray of length 1 would have sum 0. But sometimes problems treat subarray of length 1 as not having any adjacent differences and thus not considered. Let's see typical problem: "number of subarrays that have a sum of absolute differences between adjacent elements equal to k". Usually they consider subarrays of any length, and for length 1, sum is 0. But need to decide. I'll check typical coding challenge: I recall a problem from LeetCode? Not sure. Let's reason: If k=0, then we want subarrays where sum of absolute differences =0. That means all adjacent differences are 0, i.e., all elements equal. So any subarray where all elements equal qualifies. That includes length 1 subarrays (trivially all equal). So if k=0, we count all constant subarrays. That's plausible. But we need to confirm from problem statement: "You are given an array of integers nums. Write a function to find the number of subarrays that have a sum of absolute differences between adjacent elements equal to a given value k." It doesn't specify length >1. So we should include length 1 when k=0. However, if k !=0, length 1 subarrays won't qualify. So we need to handle that.
Thus we need to count number of subarrays [i, j] such that sum_{t=i}^{j-1} |nums[t] - nums[t+1]| = k.
Let's denote an array of differences: d[i] = |nums[i] - nums[i+1]| for i=0 to n-2. Then the condition for subarray [i,j] (with i<j) is sum_{t=i}^{j-1} d[t] = k. For subarray of length 1 (i=j), sum is 0, so if k=0, count them. But note that subarrays of length 1 correspond to no d elements. So we can count separately: if k==0, count all n length-1 subarrays plus other subarrays where sum of d =0 (which would be subarrays where all adjacent differences are zero, i.e., all elements equal). Actually if sum of d over some interval =0, then all d in that interval must be 0 because they are non-negative. So that means all consecutive pairs in that interval have zero difference, meaning the entire subarray is constant. So we need to count all subarrays consisting of identical numbers. That's a separate count. But we can also treat d sum as 0 for any interval of d's (i.e., subarray length >=2) only if all d's are zero. So we could count them along with length-1 if k=0.
Alternatively, we can consider the problem as counting intervals in the d array that sum to k, and also possibly the single-element subarrays if k=0. But note: subarray [i,j] in original nums corresponds to a consecutive range of d from i to j-1. So any subarray of original nums of length L corresponds to L-1 d's. So we need to count pairs (i,j) with i <= j such that sum_{t=i}^{j-1} d[t] = k. For i=j, the sum is empty = 0. So for k=0, i=j count includes n such subarrays. Additionally, for i<j, we need sum of d's over that interval = 0, which implies all d in that interval are 0. So any interval of d where all values are zero qualifies. That corresponds to original subarrays where all elements equal. For length >=2, they are also counted.
Thus the total count = (if k==0: n + number of intervals in d with sum=0) else number of intervals in d with sum=k.
But careful: For k=0, the intervals in d with sum=0 are exactly those intervals where all d[t] =0. So if we count all subarrays of original that are constant, that's easier: we can compute runs of equal numbers. For a run of length L (maximal constant segment), number of subarrays that are constant = L*(L+1)/2. That includes length 1. So total constant subarrays = sum over runs L*(L+1)/2. That matches n + number of intervals in d with sum 0? Let's see: For a run of length L, number of subarrays of length >=2 that are constant = L*(L-1)/2. That's number of intervals in d (the d's within that run are all zero) that are non-empty. The number of intervals in d that are all zero across runs: For each run of length L, the number of sub-intervals (i.e., contiguous subsets) of d within that run = L-1 choose 1? Actually d indices within the run: there are L-1 d values, all zero. Number of intervals (contiguous) in that block of length L-1 is (L-1)L/2. Wait, formula: number of contiguous subarrays of an array of length m is m(m+1)/2. So for m = L-1, number of intervals of d (non-empty) is (L-1)*L/2. That equals number of subarrays of original of length >=2 within that run. Yes. So total intervals in d with sum=0 across the whole array = sum over runs (L-1)L/2. Then total constant subarrays = n + that? Actually n + sum over runs (L-1)L/2 = sum over runs [L + (L-1)L/2] = sum over runs [L(1 + (L-1)/2)] = sum over runs [L( (2 + L-1)/2 )] = sum over runs [L(L+1)/2] which matches total constant subarrays. So indeed.
So we can either compute d and count subarrays (intervals) with sum = k, plus for k=0 also include single-element subarrays? Wait careful: Counting intervals in d of sum=k gives us subarrays of original with length >=2. For k=0, intervals in d with sum=0 includes all intervals where d all zero. That counts subarrays of length >=2 that are constant. But we also need to count length-1 subarrays for k=0. That's n. So total for k=0 = n + count_d_intervals_sum_0.
Alternatively, we can avoid special case by defining an extended array d' with something? But easier: compute count of intervals in d that sum to k. If k=0, then add n. But wait: Could there be intervals of d with sum 0 that include some d>0? No, because d are nonnegative. So sum=0 iff all d in interval are 0.
Now, the problem: we need to count subarrays of the original nums such that sum of absolute differences between adjacent elements = k. That is exactly counting intervals in d that sum to k. And for length 1, it's 0, so they only count if k=0. So our approach is correct.
Now, the array d can be up to length n-1. n can be? Not given. Usually we need efficient solution, maybe O(n) or O(n log n). Counting subarrays with sum = k in an array of nonnegative numbers? Actually d are nonnegative because absolute differences. So it's a classic problem: count subarrays with sum equal to k in an array of nonnegative integers. That can be done with two pointers sliding window because all numbers >=0. That yields O(n). But careful: The standard sliding window works for nonnegative numbers to count subarrays with sum exactly k. Yes, because if all numbers are nonnegative, we can use a sliding window: maintain start pointer, expand end, keep sum, when sum > k, move start forward until sum <= k, and count when sum == k. But that works when numbers are nonnegative and we count subarrays with sum <= something? Actually typical sliding window for "subarray sum equals k" with all nonnegative: we can use two pointers to find all subarrays with sum <= k, but for exact k we need to adjust. Actually we can do: for each end, we maintain start such that sum >= k? Let's recall: For nonnegative array, we can use sliding window to find subarrays with sum exactly k: For each left pointer, we can expand right until sum >= k, then if sum == k, count one, then move left? But that's not O(n) because we might need to consider multiple right for each left? There's a standard method: Use two pointers l and r, maintain sum of window [l, r). For each l, we move r until sum >= k. If sum == k, then we count that subarray. Then we subtract nums[l] from sum and increment l. But that counts each subarray exactly once? Let's test with example: nums = [1,0,1], k=1. d = [|1-0|=1, |0-1|=1] Actually original: we want subarrays with sum of d = 1. The d array: [1,1]. Two subarrays of d: [1] (sum=1) and [1] (the second element) sum=1, also the full [1,1] sum=2 not counted. So answer =2. Applying sliding window: l=0, r=0 sum=0. Expand r while sum < k: r=1 sum=1, now sum ==k -> count++. Then we subtract nums[l] (d[0]=1) from sum, sum becomes 0, l=1. Now sum=0 <k, expand r: r=2 sum=1 (adding d[1]), sum==k -> count++. Subtract d[1] sum=0 l=2, exit. Count=2. Works.
But careful: What if there are zeros in d? Then sliding window might count multiple subarrays for same start? Example: d=[0,0,0], k=0. Nonnegative. For each start, we need to count intervals with sum=0. But any interval of zeros has sum 0. The number of intervals is m*(m+1)/2=6 for m=3. Using sliding window approach: we want sum exactly 0. We start l=0,r=0 sum=0. Since sum==k, we count? But we haven't added any element yet (empty interval)? We should not count empty interval. The sliding window approach typical for nonnegative and sum=k with k>0 often assumes k>0? But if k=0, we need to be careful because empty subarray (i.e., no elements) sum=0 but we shouldn't count it because subarray must be non-empty? For d, we consider intervals that correspond to subarrays of original of length >=2. So intervals in d must be non-empty (at least one d element). So we want to count non-empty contiguous subarrays of d that sum to k. For k=0, that means all d in interval are zero. We can handle k=0 separately perhaps, or adjust sliding window to avoid empty.
The sliding window technique for k=0: We could count subarrays with sum 0 by counting runs of zeros: For each maximal run of zeros of length m, number of subarrays within it = m*(m+1)/2. That's O(n). So we can handle k=0 as a special case. For k>0, sliding window works.
But we also need to consider that k could be zero? The problem statement doesn't restrict k. So we must handle k=0.
Alternatively, we could use prefix sum and hashmap to count subarrays with sum=k. That works for any integers, including negative? But here d are nonnegative, but using hashmap is O(n) on average. However, since d are nonnegative, sliding window O(n) is deterministic and simpler. But if k=0, sliding window with nonnegatives? Let's think: if k=0, we need to count intervals with sum 0. Since numbers are nonnegative, sum zero implies all elements zero. So we can count runs of zeros. That's easy. So we can do:
If k == 0:
// count all subarrays with all equal elements (constant subarrays)
// or compute runs of zeros in d.
total = 0
// count length-1 subarrays? Wait: if k=0, we count subarrays of original with sum of d =0. That includes length 1 subarrays? Because for length 1, there are no d's, sum=0. So yes they count.
// So we need to count constant subarrays (including length1).
// As derived: compute runs of equal numbers. For each run length L, add L*(L+1)/2.
That's straightforward.
If k > 0:
// count subarrays of d (non-empty) that sum to k.
// Use sliding window.
left=0, sum=0, count=0.
for right in 0..len(d)-1:
sum += d[right]
while sum > k and left <= right:
sum -= d[left]
left += 1
// Now sum <= k
if sum == k:
count += 1
Return count.
But does this count all subarrays? Let's test with d = [2,1,3], k=3. Subarrays: [2] sum2, [2,1] sum3 -> count1, [1] sum1, [1,3] sum4, [3] sum3 -> count2. So answer 2. Sliding window: l=0, r=0 sum=2 <3, no count. r=1 sum=3 -> count++ (subarray d[0..1]). Then we continue: while sum>k? no. Then r=2 sum=6 >k -> while: subtract d[0]=2 sum=4 left=1; still >k -> subtract d[1]=1 sum=3 left=2; now sum==k, count++ (subarray d[2..2]? Actually after moving left to 2, window is [2..2]? Wait we have r=2, left=2, sum=d[2]=3. So count++ corresponds to subarray [2..2] (single element). That's [3] sum=3. So total 2. Good.
But what about d=[1,0,2], k=2. Subarrays: [1] sum1, [1,0] sum1, [1,0,2] sum3, [0] sum0, [0,2] sum2, [2] sum2. So two subarrays: [0,2] and [2]. Sliding window: l=0, r=0 sum=1<2. r=1 sum=1 (since d[1]=0). sum still 1. r=2 sum=3>2. While: subtract d[0]=1 sum=2 left=1. Now sum==2 count++: subarray from left=1 to r=2: d[1..2] = [0,2] sum2. Good. Now continue loop? r is at end. But we missed subarray [2] alone? After counting, we don't adjust left further because sum==k and we didn't subtract. Then after counting, we go to next iteration? Loop ends because r=2 is last. Did we count [2]? Not yet. Because after counting we didn't subtract anything to move left. Actually we need to continue: after counting, we still in same iteration? Our algorithm: for each right, after adjusting left so sum <= k, if sum==k count++. That's it. For r=2, after adjusting left to 1, sum=2, we count one. That's [1..2] = [0,2]. But we haven't considered that we could also have subarray [2..2] alone. To get that, we would need to also move left further to 2 and see if sum==k again. But our while loop only reduces sum until <=k. After we got sum==k, we didn't continue to reduce left because condition sum>k is false. So we only count the current window [left..right]. But there could be multiple windows ending at right that sum to k? Because if there are zeros, we might have multiple left positions giving sum==k. For nonnegative numbers, when sum==k, if we move left forward and subtract a zero, sum remains k, so there might be more subarrays ending at right with sum k. For example d=[0,0,0], k=0: for each right, we want to count all subarrays ending at right that sum to 0. Our algorithm as described for k>0 would not handle zeros properly because sum could be less than k but zeros cause sum to stay same. But we said for k>0 we can use sliding window? Let's analyze: For k>0 and array with zeros, there could be multiple left positions that yield sum=k for a fixed right. For example d=[1,0,0,1], k=1. Subarrays: [1] (first), [1,0], [1,0,0], [0,0,1]? Actually careful: d[0]=1, d[1]=0, d[2]=0, d[3]=1. Subarrays with sum=1: [1] (at index0), [1,0] (0-1), [1,0,0] (0-2), [0,0,1] (1-3) sum=1? 0+0+1=1 yes, [0,1] (2-3) sum=1, [1] at index3. So total? Let's enumerate all non-empty subarrays: indices:
0:1 ->1
0-1:1 ->1
0-2:1 ->1
0-3:2
1:0 ->0
1-2:0
1-3:1 ->1
2:0
2-3:1 ->1
3:1 ->1
So sum=1 subarrays: [0], [0-1], [0-2], [1-3], [2-3], [3] total 6? Wait [0] is index0? Actually subarray of d is contiguous index set. So we have:
[0] (just d[0]) sum1 -> count
[0,1] sum1 -> count
[0,1,2] sum1 -> count
[1,2,3] sum1 -> count
[2,3] sum1 -> count
[3] sum1 -> count
So total 6. Our sliding window approach described earlier would only count at most one per right? Let's simulate: l=0,sum=0.
r=0: add 1 sum=1. while sum>k? no. sum==k -> count++ (window [0..0]) count=1.
r=1: add 0 sum=1. while sum>k? no. sum==k -> count++ (window [0..1]) count=2.
r=2: add 0 sum=1. while sum>k? no. sum==k -> count++ (window [0..2]) count=3.
r=3: add 1 sum=2 >k. while sum>k: subtract d[0]=1 sum=1 l=1. Now sum==k -> count++ (window [1..3]) count=4.
After that, r=3 iteration ends. We have counted only 4 subarrays: [0], [0-1], [0-2], [1-3]. But we missed [2-3] and [3] because after we subtracted d[0], we got sum==k and counted window [1..3]. But we didn't further reduce left to see if [2..3] also sums to 1? Because after counting, sum==k, but left=1, sum=1. If we subtract d[1]=0, sum remains 1, left=2, then sum==k again, we should count [2..3]. Similarly subtract d[2]=0 gives left=3, sum=1 count [3..3]. But our while loop condition only runs while sum > k, not while sum == k. So we need to handle zeros: multiple left positions can yield same sum because adding zeros doesn't change sum. To count all subarrays ending at r with sum=k, we need to know how many left positions such that sum_{left..r} = k. That's essentially prefix sum counting: count of l such that prefix[r+1] - prefix[l] = k, i.e., prefix[l] = prefix[r+1] - k. Since d are nonnegative, prefix is non-decreasing. Actually d[i]>=0, so prefix is monotonic non-decreasing. That property allows us to count with two pointers but we need to account for zeros.
We can modify sliding window: For each right, after ensuring sum <= k, we want to find the smallest left such that sum_{left..right} <= k? Actually we want all left' such that left' in [left, right] and sum_{left'..right} == k. Since prefix is non-decreasing, the sum_{left'..right} = prefix[right+1] - prefix[left']. The prefix is non-decreasing, and left' can be as large as the point where prefix[left'] is just <= prefix[right+1] - k? Wait, sum == k => prefix[left'] = prefix[right+1] - k. Since prefix is non-decreasing, there might be a range of left' that yield same prefix value if there are zeros. Indeed, if there are zeros in d, prefix may stay constant over some indices. So the number of left' with prefix[left'] = target = number of indices where prefix equals that value. That's a range. Our sliding window with two pointers only tracks one left pointer (the smallest such that sum <= k? Actually we move left while sum > k to get sum <= k. That gives left = smallest index such that sum_{left..right} <= k? Not exactly: we start with left from previous iteration, we add d[right], then while sum>k we increment left. After that, sum <= k. But if sum == k, then left is the smallest index such that sum_{left..right} <= k? Let's analyze: Since we increment left only when sum>k, after loop sum <= k, and if we were to decrement left (if left>0) sum would be sum + d[left-1] maybe >? Not necessarily. Actually because we only stop when sum <= k, but left is the minimal index we have moved to ensure sum <= k? Consider we had sum > k, we remove from left until sum <= k. After that, if we move left one less (i.e., left-1), the sum would be sum + d[left-1] which was > k? Actually if we stopped because sum <= k, the previous state before removing the last d (that made sum <=k) was sum > k. So after removal, sum <= k. So if we try to add back that d, sum would become > k. So the current left is the smallest index such that sum_{left..right} <= k? Not exactly: If sum == k, then if we try to include one more element to the left (i.e., reduce left by 1), the sum would be > k because we previously removed that element because sum was > k. So yes, left is the smallest index such that the sum of window from left to right is <= k. Actually we may have also case where initially sum <= k without any removal; left might be from previous iteration where sum <= k. But it may not be smallest if there are zeros at left that we could remove without changing sum. For example, after previous iteration, left might be at a position where d[left]=0, and sum is still k. If we move left forward over zeros, sum stays k. So we may have multiple left positions that give sum=k. Our algorithm only counts the current left, not the other ones. So we need to count the number of left positions such that sum_{left..right} == k.
We can adapt: Since prefix is non-decreasing, we can for each right, we want to count how many left such that prefix[right+1] - prefix[left] = k => prefix[left] = prefix[right+1] - k. Since prefix is non-decreasing, we can maintain a map of counts of prefix values we have seen (for indices from 0 up to some left? Actually we need prefix[left] for left from 0 to right? left can be from 0 to right inclusive? Because subarray d[left..right] uses prefix[left] as prefix sum before left. Standard method: For an array, count subarrays with sum k using prefix sums and hashmap: count of prefix sums such that prefix[j] - prefix[i] = k, i<j. That's O(n) and works for any numbers. Since we only need for d array, we can use that. And it handles zeros naturally. Since d length up to n-1, O(n) time and space. That's simpler and robust. Also for k>0, works. For k=0, using prefix sums, we would count intervals where prefix[j] == prefix[i] (i<j). That counts all intervals with sum 0, which includes those with all zeros? Actually any subarray with sum 0 in nonnegative array must have all zeros, so that's fine. But also empty? We consider i<j, non-empty. So that's fine. But we also need to include length-1 subarrays of original if k=0. But if we count intervals in d, we get subarrays of original length>=2. So we need to add n separately for length-1 if k=0. But wait: The prefix sum method for d with k=0 will count all intervals (i,j) of d (i<j) such that sum_{i..j-1}? Actually careful: Standard prefix sum for array A of length m: define prefix[0]=0, prefix[i]=A[0]+...+A[i-1] for i=1..m. Then subarray A[l..r] (0<=l<=r<m) has sum = prefix[r+1]-prefix[l]. So we count pairs (l, r) with l <= r such that prefix[r+1]-prefix[l]=k. That counts non-empty subarrays. So for d, m = n-1. So using prefix sum method we count all non-empty intervals in d with sum k. For k=0, that gives all intervals of d with sum zero, i.e., all intervals of zeros. That's exactly the number of subarrays of original with length >=2 that are constant. Then we need to add n for length-1 subarrays if k=0. So total = n + count_d_intervals_sum_0.
Alternatively, we could incorporate length-1 subarrays by extending d? No.
So solution: compute d array, then use prefix sum hashmap to count subarrays with sum = k. For k>0, that's answer. For k==0, answer = count + n.
But careful: What about subarrays of original with length 1 are counted even if k>0? No because sum is 0, not equal to k>0. So not counted.
Edge cases: n=0? Probably n>=1. If n=1, d array empty. Then:
If k==0: we have one subarray (the single element) count=1.
If k>0: count=0.
But careful: The constant subarray counting with runs: If n=1, there is one run of length 1, so total constant =1, which matches.
But if we use d prefix sum method: d empty -> count_d_intervals_sum_0 =0. Then if k==0, total = n + 0 =1. Works.
If n>1, we compute d and prefix sums.
Complexity: O(n) time, O(n) space for hashmap (or O(1) if we use two pointers with special handling for zeros? But prefix sum method is simpler and O(n) space, acceptable). However, we can also use two pointers with counting zeros: We can maintain left pointer and also count how many consecutive zeros at left? Actually we can adjust sliding window to count multiple lefts: when sum==k, we can move left forward as long as d[left]==0, because removing zero doesn't change sum, so each such left' yields a valid subarray. So we could count: while sum==k, we can count one, then if d[left]==0, subtract zero and left++, count again, etc. But careful: after counting one, if we move left over zeros, we get more subarrays ending at right. That would still be O(n) because each element moved left at most once. That could work. But easier to just use prefix sum.
Since d values are nonnegative, prefix sums are non-decreasing, we could also use two pointers without hashmap but with counting zeros: Actually we need to count all left indices such that prefix[left] = prefix[right+1] - k. Since prefix is non-decreasing, the set of left indices that give a particular prefix value form a contiguous block (maybe multiple indices with same prefix due to zeros). We can maintain a hashmap of prefix counts, that's straightforward.
So we'll implement:
def count_subarrays_abs_diff_sum(nums, k):
n = len(nums)
if n == 0:
return 0
# Compute d array
d = [abs(nums[i] - nums[i+1]) for i in range(n-1)]
m = n-1
# Special case: if k==0, we need to include length-1 subarrays.
# But we can compute count from d intervals with sum k using prefix sum.
from collections import defaultdict
prefix_counts = defaultdict(int)
prefix_counts[0] = 1 # prefix[0] = 0
prefix_sum = 0
count_d = 0
for val in d:
prefix_sum += val
target = prefix_sum - k
count_d += prefix_counts.get(target, 0)
prefix_counts[prefix_sum] += 1
if k == 0:
# Include subarrays of length 1
return count_d + n
else:
return count_d
But check: For k=0, prefix_counts counts intervals in d with sum 0. That includes intervals where sum=0, which are non-empty intervals of zeros. That's correct. Then we add n. Works.
But what if k is negative? Problem statement: k is given value. Could be negative? Sum of absolute differences is nonnegative, so if k < 0, answer should be 0. But maybe k is nonnegative. We can handle: if k<0 return 0. But typical constraints: k is nonnegative integer. We'll include check.
Test:
Example1: nums = [1,2,3], d = [1,1]. k=2? Subarrays of original: length>=2: [1,2,3] sum of diffs = |1-2|+|2-3| =1+1=2. Also [1,2] sum=1, [2,3] sum=1. So count=1. Our method: prefix: start with {0:1}. prefix_sum after first=1: target=1-2=-1 count0. add prefix[1]=1. second: prefix_sum=2, target=2-2=0, prefix_counts[0]=1 => count=1. So count_d=1. k!=0 so answer=1. Good.
Example2: nums = [5,5,5,5], d=[0,0,0], n=4. For k=0: constant subarrays: total = 4*(4+1)/2=10. Our method: count_d intervals sum0: number of non-empty subarrays of d: length m=3 => 3*4/2=6. Then + n =4 =>10. Good.
For k>0, e.g., k=1: d all zeros, count_d =0. answer=0.
Example3: nums=[1,3,2,4], d=[2,1,2]. Let's compute manually for k=3: subarrays:
Original length>=2:
[1,3] sum=2
[1,3,2] sum=2+1=3 -> count
[1,3,2,4] sum=2+1+2=5
[3,2] sum=1
[3,2,4] sum=1+2=3 -> count
[2,4] sum=2
So count=2. Using prefix: prefix[0]=0; after d0=2, prefix=2; target=2-3=-1 count0; record {2:1}. d1=1, prefix=3; target=3-3=0 -> prefix_counts[0]=1 => count1. record {3:1}. d2=2, prefix=5; target=5-3=2 -> prefix_counts[2]=1 => count2. So 2. Good.
Example4: zeros in d: nums = [1,1,2,2,3,3] => d=[0,1,0,1,0]? Actually differences: |1-1|=0, |1-2|=1, |2-2|=0, |2-3|=1, |3-3|=0 => d=[0,1,0,1,0]. n=6. Let's compute k=1. We need subarrays of original where sum of abs diffs =1. Equivalent to intervals in d sum=1. Count intervals with sum 1. Let's enumerate: d intervals of sum 1:
Single element 1 at index1 and index3: [1] and [3] =>2.
Intervals that include a 1 and surrounding zeros but total sum=1: e.g., [0,1] (index0-1) sum=1, [1,0] (1-2) sum=1, [0,1,0] (0-2) sum=1, [0,1] at indices2? Actually index2 is 0, index3 is 1, index4 is 0. So intervals: [2,3] (0+1)=1, [3,4] (1+0)=1, [2,3,4] (0+1+0)=1, also [0,1,2]? That's 0+1+0=1? Wait indices: 0:0,1:1,2:0 => sum=1 => yes. Also [1,2] =1+0=1; [0,1,2]? That's length3: sum=1. So many. And also [1,2,3]? 1+0+1=2 >1. [0,1,2,3] sum=2. So need to count all contiguous subarrays of d that sum to 1. That's a classic counting with prefix sums. Let's compute using prefix method:
prefix[0]=0
i0: d0=0, p=0. target = 0-1 = -1 => count0. prefix[0] occurs again? Actually we need to store prefix after each element. Typically we do: for each val, update prefix, then count prefix_counts[prefix - k], then increment prefix_counts[prefix]. So:
Initialize prefix_counts{0:1}
prefix=0
val=0: prefix=0, target= -1 -> count0, prefix_counts[0]=2 now.
val=1: prefix=1, target=0 -> count+=prefix_counts[0]=2 => count=2, prefix_counts[1]=1
val=0: prefix=1, target=0 -> count+=prefix_counts[0]=2 => count=4, prefix_counts[1]=2 now (since we increment after counting? Actually we need to increment after counting. Let's be systematic:
Step1: val=0:
prefix=0+0=0
target = 0 - 1 = -1 => add 0
prefix_counts[0] currently 1 -> then increment: prefix_counts[0]=2
count=0
Step2: val=1:
prefix=0+1=1
target=1-1=0 => prefix_counts[0]=2 => count=2
increment prefix_counts[1] = 1
Step3: val=0:
prefix=1+0=1
target=1-1=0 => prefix_counts[0]=2 => count=4
increment prefix_counts[1] = 2 (since now prefix 1 appears again)
Step4: val=1:
prefix=1+1=2
target=2-1=1 => prefix_counts[1]=2 => count=6
increment prefix_counts[2]=1
Step5: val=0:
prefix=2+0=2
target=2-1=1 => prefix_counts[1]=2 => count=8
increment prefix_counts[2]=2
Total count_d=8. So answer=8 (since k=1>0). Let's manually verify: list all intervals of d with sum 1:
Indices:0,1,2,3,4
All subarrays:
Length1: index1 (1), index3 (1) =>2
Length2: [0,1]=1, [1,2]=1, [2,3]=1, [3,4]=1 =>4
Length3: [0,1,2]=1, [1,2,3]=? 1+0+1=2 no, [2,3,4]=1 =>2
Length4: [0,1,2,3]=1+0+1? Actually 0+1+0+1=2, no. [1,2,3,4]=1+0+1+0=2 no.
Length5: sum=2? Actually 0+1+0+1+0=2 no.
Total =2+4+2=8. matches.
Thus prefix sum method works.
Now, we need to write a function in some language (likely Python). Also explain algorithm.
We'll produce solution with steps:
If len(nums) <= 1: if k==0 return 1 else 0. But we can still compute d and handle.
Compute differences array d of length n-1.
Use prefix sum counting to find number of non-empty subarrays of d that sum to k. But careful: if k<0, return 0.
If k==0, result = count_d + n (since each single-element subarray qualifies). If k>0, result = count_d. If k<0, result = 0.
But is there any scenario where subarray of original length >=2 but sum of abs diffs =0 but not all elements equal? Since abs diffs are nonnegative, sum=0 implies each diff =0, so all elements equal. So it's consistent.
One more nuance: When k>0, do we need to consider subarrays of length 1? No.
Edge case: n=1 and k=0 -> answer 1; n=1 and k>0 -> 0.
Implementation details:
Use dictionary to store counts of prefix sums encountered so far. Initialize with prefix_counts[0]=1.
Iterate through d, updating current prefix sum.
For each step, compute needed = current_prefix - k. If needed exists in map, add its count to answer.
Then increment count for current_prefix.
Complexities: O(n) time, O(n) space.
Now produce final answer with explanation.
But we should also consider if the problem might want to include subarrays of length 1 only when k=0? Yes.
Let's also check if the problem statement says "sum of absolute differences between adjacent elements". For a subarray of length 1, there are no adjacent elements, so sum could be considered 0 or undefined. Usually it's considered 0 (empty sum). So including them for k=0 is logical.
We'll include that in explanation.
Now, I'll craft a response: function definition, algorithm explanation, complexity analysis, and maybe some test cases.
We'll produce Python code:
def count_subarrays_with_abs_diff_sum(nums, k):
n = len(nums)
if n == 0:
return 0
# If k is negative, impossible because sum of absolute differences >=0
if k < 0:
return 0
# Build differences array
d = [abs(nums[i] - nums[i+1]) for i in range(n-1)]
# Count subarrays of d with sum = k
from collections import defaultdict
prefix_counts = defaultdict(int)
prefix_counts[0] = 1
prefix = 0
count_d = 0
for val in d:
prefix += val
target = prefix - k
count_d += prefix_counts.get(target, 0)
prefix_counts[prefix] += 1
# For k==0, add subarrays of length 1 (each single element)
if k == 0:
return count_d + n
else:
return count_d
But wait: For k==0, count_d already counts subarrays of d with sum=0. That includes intervals of d of any length (non-empty). That corresponds to subarrays of original length>=2 with all equal elements. Then we add n. So total = constant subarrays count. That's correct.
But we need to be careful: For k==0, the prefix sum counting method counts intervals of d with sum=0. However, we must ensure that we are counting only non-empty intervals. Our method counts non-empty because we only consider pairs i<j where subarray from i to j-1? Actually prefix subtraction: for each index r (0-indexed d), we consider prefix[r+1] - prefix[l] = k. Here l can be from 0 to r inclusive? Actually prefix array of length m+1. At step r, we have current prefix = prefix[r+1] (sum of first r+1 elements). We look for prefix[l] = current_prefix - k, where l can be any index from 0 to r+1? Let's see: We have prefix_counts storing prefix values for indices up to the current index (including current?). In the loop, we first compute current prefix (which is prefix after including current element). Then we query prefix_counts for target. The prefix_counts currently contain prefix values from indices 0 up to r (since we haven't added current prefix yet). That means l can be any index from 0 to r. That yields subarrays from l to r inclusive? Actually if prefix[l] is stored, then subarray from l to r (inclusive) sum = prefix[r+1] - prefix[l]. That's correct because prefix[r+1] is after including d[r]. So l can be r+1? No, l <= r. So subarray is non-empty because r+1 > l. So we are counting non-empty subarrays of d. Good.
Thus count_d is non-empty intervals.
Now check for k==0: count_d includes intervals of d of length >=1 that sum to 0. That is correct.
Now, add n for length-1 subarrays.
Edge case: if n=1, d empty. Loop does nothing, count_d=0. For k=0, return n+0=1. For k>0, return 0. Good.
Edge case: k>0 and d empty -> return 0.
Now, we must ensure that for k==0, the prefix sum counting with k=0 also counts intervals with sum 0, which as said is intervals of zeros. But note: If there are zeros in d, our prefix sum method will count them. For instance d=[0,0], k=0: prefix_counts initialized {0:1}. Loop:
val=0: prefix=0, target=0-0=0 => count += prefix_counts[0] = 1 => count_d=1. Then prefix_counts[0] becomes 2.
val=0: prefix=0, target=0 => count += prefix_counts[0] = 2 => count_d=3. Then prefix_counts[0]=3.
So count_d=3. But m=2, number of non-empty subarrays of d with sum 0 should be 3 (since 2 zeros: subarrays: [0], [0], [0,0] total 3). Yes. So count_d=3. Then add n= (if original n? For n such that d length 2, n=3). So total constant subarrays = 3 + 3? Actually n=3, constant subarrays: run of length 3 => 3*4/2=6. But we have count_d=3 and n=3 -> total 6. Good.
So works.
Now, let's test a more complex: nums=[1,2,2,1], d=[1,0,1]. For k=1: subarrays of d sum=1: [0] first 1, [0,1]? Actually d[0]=1 -> sum1; d[0..1]=1+0=1; d[1..2]=0+1=1; d[2]=1. Also maybe [0..2]=1+0+1=2 not. So count=4. Prefix method:
prefix_counts{0:1}
val=1: p=1 target=0 => count+=1 =>1; prefix_counts[1]=1
val=0: p=1 target=0 => count+=prefix_counts[0]=1 =>2; prefix_counts[1]=2
val=1: p=2 target=1 => count+=prefix_counts[1]=2 =>4; prefix_counts[2]=1
count_d=4. Good.
Now original subarrays length>=2 that sum to 1: [1,2] sum1; [1,2,2] sum1; [2,2] sum0; [2,2,1] sum1? Actually [2,2,1]: diffs: |2-2|=0, |2-1|=1 => sum1; [2,1] sum1. Also [1,2,2,1] sum1+0+1=2. So count= [1,2], [1,2,2], [2,2,1], [2,1] =4. Works.
So solution correct.
Now we need to provide function and explanation.
We should also consider time complexity O(n) and space O(n) for hashmap.
We might also note that if we want O(1) space, we could use two pointers with zero-run counting but that's a bit more complex. The problem likely expects O(n) time and possibly O(n) space.
Now produce final answer: We'll write a Python function with docstring.
Also include explanation of algorithm: convert to differences array, use prefix sum hashmap to count subarrays with sum k. For k=0 add single element subarrays.
But careful: The prefix sum method for k=0 also counts intervals of d that sum 0. But are those the only subarrays of original with sum 0? Yes, because any subarray of original with length >=2 must have sum of d=0 only if all d in that interval are zero. So it's captured.
Thus final.
But wait: Is there any chance of integer overflow? Not in Python.
Now produce final answer.
Solution Explanation
For a subarray nums[i … j] ( i ≤ j ) we consider the sum of absolute
differences between consecutive elements:
For a subarray of length 1 there are no pairs, the sum is defined as 0.
All |nums[t] – nums[t+1]| are non‑negative, therefore S(i, j) ≥ 0.
The task: count how many subarrays satisfy S(i, j) = k.
1. Reduce to a classic subarray‑sum problem
Create an auxiliary array d of length n‑1 (where n = len(nums)):
code
d[t] = |nums[t] – nums[t+1]| for t = 0 … n-2
For any subarray nums[i … j] with i < j we have
code
S(i, j) = d[i] + d[i+1] + … + d[j-1]
Thus each subarray of length ≥ 2 of nums corresponds exactly to a
non‑empty contiguous subarray of d, and the required sum is the sum of
that d‑subarray.
Subarrays of length 1 of nums have S = 0. They are relevant only when
k = 0.
So the problem becomes:
Count the number of non‑empty subarrays of d whose elements sum to k.
If k = 0 we must additionally add n (all single‑element subarrays).
2. Counting subarrays with a given sum (prefix‑sum + hashmap)
While scanning d from left to right we maintain a hash map cnt
where cnt[x] is the number of prefix values equal to x seen so far
(including the initial pref[0]=0).
When we have just computed cur = pref[r+1], the number of left borders
l that produce a valid subarray ending at r is exactly cnt[cur – k].
Algorithm:
code
cnt = {0 : 1} # pref[0] = 0 already seen
cur = 0
answer_d = 0 # subarrays of d with sum k
for value in d:
cur += value
target = cur - k
answer_d += cnt.get(target, 0)
cnt[cur] = cnt.get(cur, 0) + 1
This counts all non‑empty subarrays of d whose sum is k.
3. Final result
code
if k < 0: answer = 0 # impossible
else:
answer = answer_d
if k == 0:
answer += n # add length‑1 subarrays of nums
4. Correctness Proof
We prove that the algorithm returns the required number of subarrays.
Lemma 1
For any i < j (original indices in nums) S(i, j) = sum(d[i … j‑1]).
Proof. By definition d[t] = |nums[t] – nums[t+1]|. The sum of absolute
differences for the subarray nums[i … j] contains exactly the terms
|nums[t] – nums[t+1]| for t = i … j‑1, which is precisely the sum of
d[i] … d[j‑1]. ∎
Lemma 2
A subarray nums[i … j] of length 1 satisfies S(i, i)=0.
Proof. There are no adjacent pairs, the empty sum equals 0. ∎
Lemma 3
The algorithm count_d computed above equals the number of non‑empty
subarrays of d whose sum is k.
Proof.
Consider the prefix array pref[0 … m]. For each index r (0‑based in d)
the algorithm sets cur = pref[r+1]. At that moment cnt contains exactly
the frequencies of pref[0] … pref[r] (because each previous step inserted
pref[t] after processing d[t‑1]).
For any left border l with 0 ≤ l ≤ r,
d[l … r] sum equals pref[r+1] – pref[l].
Thus d[l … r] sums to k iff pref[l] = cur – k.
The number of such l is cnt[cur – k], which the algorithm adds to
answer_d. Every pair (l, r) with l ≤ r is considered exactly once,
namely when r is processed. Therefore answer_d counts all
non‑empty subarrays of d with sum k. ∎
Lemma 4
If k = 0, the total number of subarrays of nums with S = 0 equals
answer_d + n.
Proof.
From Lemma 1, any subarray of length ≥ 2 has S = sum(d[l … r]). Such a
subarray has S = 0 iff the corresponding d‑subarray sum is 0. By Lemma 3,
answer_d counts exactly those.
Subarrays of length 1 (there are n of them) have S = 0 by Lemma 2.
No other subarray exists. Hence total = answer_d + n. ∎
Lemma 5
If k > 0, the total number of subarrays of nums with S = k equals
answer_d.
Proof.
Length 1 subarrays have S = 0 ≠ k. Any subarray of length ≥ 2 corresponds
bijectively to a non‑empty subarray of d (Lemma 1). Its sum equals k
iff the d‑subarray sum is k. Lemma 3 states that answer_d counts
exactly those. ∎
Lemma 6
If k < 0, there is no subarray with S = k.
Proof. All absolute differences are non‑negative, hence any sum S
is ≥ 0. ∎
Theorem
The function count_subarrays_with_abs_diff_sum(nums, k) returns the
exact number of subarrays of nums whose sum of absolute differences
between adjacent elements equals k.
Proof.
Three cases:
k < 0: function returns 0 by Lemma 6, correct.
k = 0: function returns answer_d + n. By Lemma 4 this equals the
desired count.
k > 0: function returns answer_d. By Lemma 5 this equals the
desired count.
Thus in all cases the returned value is correct. ∎
5. Complexity Analysis
Building d: O(n) time, O(n) space (actually n‑1 elements). Prefix‑sum counting: one pass over d, O(m) = O(n) time, hash map stores
at most m+1 distinct prefix sums → O(n) extra space.
Overall:
Time: O(n)
Space: O(n) (can be reduced to O(1) with a two‑pointer trick,
but O(n) is perfectly acceptable)
6. Reference Implementation (Python 3)
python
from collections import defaultdict
from typing import List
def count_subarrays_with_abs_diff_sum(nums: List[int], k: int) -> int:
"""
Returns the number of subarrays of `nums` for which the sum of absolute
differences between adjacent elements equals `k`.
"""
n = len(nums)
if n == 0:
return 0
if k < 0:
return 0
# Differences array d[t] = |nums[t] - nums[t+1]|
d = [abs(nums[i] - nums[i + 1]) for i in range(n - 1)]
m = n - 1
# Count non‑empty subarrays of d whose sum is exactly k
prefix_counts = defaultdict(int)
prefix_counts[0] = 1 # pref[0] = 0
cur = 0
count_d = 0
for val in d:
cur += val
target = cur - k
count_d += prefix_counts.get(target, 0)
prefix_counts[cur] += 1
# If k == 0, we must also count all single‑element subarrays of nums
if k == 0:
return count_d + n
else:
return count_d
Explanation of the code follows directly the algorithm proven correct
above.