Count Subarrays with Distant Sums Problem
Description
LeetCode Problem 4051.
You are given an integer array nums and two integers goal and k.
A subarray nums[i..j] is considered distant if the absolute difference between its sum and goal is at least k.
Return the number of distant subarrays.
Example 1:
Input: nums = [1,2,1], goal = 4, k = 1
Output: 5
Explanation:
The distant subarrays for k = 1 are:
i j nums[i..j] Sum abs(sum - goal)
0 0 [1] 1 3
1 1 [2] 2 2
2 2 [1] 1 3
0 1 [1, 2] 3 1
1 2 [2, 1] 3 1
Thus, the answer is 5.
Example 2:
Input: nums = [2,-1,3], goal = 2, k = 2
Output: 2
Explanation:
The distant subarrays for k = 2 are:
i j nums[i..j] Sum abs(sum - goal)
1 1 [-1] -1 3
0 2 [2, -1, 3] 4 2
Thus, the answer is 2.
Example 3:
Input: nums = [-3,1,2], goal = 0, k = 3
Output: 2
Explanation:
The distant subarrays for k = 3 are:
i j nums[i..j] Sum abs(sum - goal)
0 0 [-3] -3 3
1 2 [1, 2] 3 3
Thus, the answer is 2.
Constraints:
1 <= nums.length <= 10^5-10^9 <= nums[i] <= 10^9-10^9 <= goal <= 10^90 <= k <= 10^9
Solution
Approach: Prefix Sums and a Binary Indexed Tree
Let s be the prefix sums of nums with s[0] = 0, so the subarray nums[L..R-1] has sum s[R] - s[L]. There are n * (n + 1) / 2 subarrays. It is easier to count the ones that are not distant, |s[R] - s[L] - goal| < k, and subtract them from the total.
That inequality says s[R] - goal - k < s[L] < s[R] - goal + k, so s[L] lies in the integer interval [s[R] - goal - k + 1, s[R] - goal + k - 1].
Go through the prefix sums from left to right. For the current value v = s[R], count how many earlier prefix sums fall in that interval and subtract the count, then insert v. To count quickly, sort the prefix sums, map each value to its position by binary search, and keep the counts in a binary indexed tree.
Complexity: O(n log n) time and O(n) space.
from bisect import bisect_left
from itertools import accumulate
class BinaryIndexedTree:
__slots__ = "n", "c"
def __init__(self, n: int):
self.n = n
self.c = [0] * (n + 1)
def update(self, x: int, delta: int) -> None:
while x <= self.n:
self.c[x] += delta
x += x & -x
def query(self, x: int) -> int:
s = 0
while x:
s += self.c[x]
x -= x & -x
return s
class Solution:
def distantSubarrays(self, nums: List[int], goal: int, k: int) -> int:
s = list(accumulate(nums, initial=0))
st = sorted(s)
n = len(nums)
ans = (1 + n) * n // 2
bit = BinaryIndexedTree(len(st) + 1)
for v in s:
a = v - goal - k + 1
b = v - goal + k - 1
l = bisect_left(st, a) + 1
r = bisect_left(st, b + 1)
if l <= r:
ans -= bit.query(r) - bit.query(l - 1)
bit.update(bisect_left(st, v) + 1, 1)
return ans