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 <= 105-109 <= nums[i] <= 109-109 <= goal <= 1090 <= k <= 109When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
The problem asks for the number of subarrays whose sum differs from a target goal by at least k in absolute value. Expressing the subarray sum as the difference between two prefix sums turns the condition into two disjoint inequalities when k is positive. We can coordinate-compress all relevant prefix sums and query bounds, then use a Fenwick tree to count satisfying starting points efficiently.
Here's how the algorithm would work step-by-step:
def count_distant_subarrays(nums, goal, k):
array_length = len(nums)
if k == 0:
return array_length * (array_length + 1) // 2
prefix_sums = [0] * (array_length + 1)
# Compute all prefix sums for the input array
for index in range(array_length):
prefix_sums[index + 1] = prefix_sums[index] + nums[index]
all_values = set(prefix_sums)
for current_sum in prefix_sums:
all_values.add(current_sum - goal - k)
all_values.add(current_sum - goal + k)
sorted_values = sorted(all_values)
value_to_rank = {val: idx + 1 for idx, val in enumerate(sorted_values)}
tree_size = len(sorted_values) + 2
fenwick_tree = [0] * tree_size
def fenwick_add(idx, delta):
while idx < tree_size:
fenwick_tree[idx] += delta
idx += idx & (-idx)
def fenwick_query(idx):
total = 0
while idx > 0:
total += fenwick_tree[idx]
idx -= idx & (-idx)
return total
total_valid_subarrays = 0
# Process prefix sums and count valid previous prefix sums
for count_seen, current_sum in enumerate(prefix_sums):
if count_seen > 0:
lower_bound_rank = value_to_rank[current_sum - goal - k]
upper_bound_rank = value_to_rank[current_sum - goal + k]
left_count = fenwick_query(lower_bound_rank)
right_count = count_seen - fenwick_query(upper_bound_rank - 1)
total_valid_subarrays += left_count + right_count
# Insert the current prefix sum into the Fenwick tree
fenwick_add(value_to_rank[current_sum], 1)
return total_valid_subarrays
The problem asks us to count the number of subarrays whose sum differs from a target goal by at least k. A subarray sum can be represented as the difference between two prefix sums, leading to two inequalities for valid earlier prefix sums. We can efficiently count matching past prefix sums using coordinate compression and a Binary Indexed Tree.
Here's how the algorithm would work step-by-step:
def count_distant_subarrays(nums: list[int], goal: int, k: int) -> int:
# Define a helper Fenwick tree (Binary Indexed Tree) for range queries.
class FenwickTree:
def __init__(self, size: int):
self.tree = [0] * (size + 1)
def add(self, index: int, value: int):
while index < len(self.tree):
self.tree[index] += value
index += index & (-index)
def query(self, index: int) -> int:
total = 0
while index > 0:
total += self.tree[index]
index -= index & (-index)
return total
prefix_sum = 0
prefix_sums = [0]
# Compute all prefix sums to identify distinct values.
for number in nums:
prefix_sum += number
prefix_sums.append(prefix_sum)
unique_values = sorted(set(prefix_sums))
from bisect import bisect_right
bit = FenwickTree(len(unique_values))
# Coordinate compression maps values to 1-based ranks.
rank_map = {val: idx + 1 for idx, val in enumerate(unique_values)}
total_distant = 0
# Iterate through prefix sums and count valid previous prefix sums.
for current_prefix in prefix_sums:
upper_limit = current_prefix - goal - k
lower_limit = current_prefix - goal + k
left_idx = bisect_right(unique_values, upper_limit)
count_left = bit.query(left_idx)
right_idx = bisect_right(unique_values, lower_limit - 1)
count_right = bit.query(len(unique_values)) - bit.query(right_idx)
total_distant += count_left + count_right
bit.add(rank_map[current_prefix], 1)
return total_distant
| Case | How to Handle |
|---|---|
| Empty or null input array | Return zero immediately as no contiguous subarrays can be formed. |
| Array with a single element | Check if the single element satisfies the condition and return one or zero accordingly. |
| Maximum-sized inputs with large values | Use 64-bit integers for running sums and sliding window boundaries to prevent arithmetic overflow. |
| Array containing all negative numbers | Ensure the sliding window or prefix sum logic correctly handles negative accumulation without breaking monotonicity. |
| Array containing zeros and mixed signs | Maintain precise boundary conditions since zeros do not change the sum but affect subarray length counts. |
| All elements are identical | Calculate combinations efficiently using mathematical formulas or optimized loops to avoid time limit exceeded errors. |
| No valid subarrays meet the criteria | Ensure the counter properly finishes scanning and returns zero without throwing null reference exceptions. |
| Extremely large sum values causing integer overflow | Cast all intermediate sum variables to long data types in languages like Java and C++. |