We need to solve: Given an array of integers nums, and integers lower and upper, count the number of subarrays (contiguous) whose sum lies in [lower, upper]. Return the count.
This is a classic problem: Count of range sum. Approach: prefix sums and using BIT/Fenwick tree or Balanced BST (like TreeMap) to count number of prefix sums that satisfy: For each prefix sum S[i], we want count of j < i such that lower <= S[i] - S[j] <= upper => S[i] - upper <= S[j] <= S[i] - lower. So as we iterate through prefix sums, we query the number of previous prefix sums in that range and add to answer, then insert current prefix sum.
We need to implement efficiently: O(n log n). Use Fenwick tree after coordinate compression of all possible prefix sums (and also S[i]-lower and S[i]-upper maybe). Or we can use a balanced BST with order statistics (like TreeMap in Java) but careful about duplicates. In C++, we can use multiset and do lower_bound/upper_bound to get count, but that would be O(n log n) but counting number of elements in range in multiset is O(distance) which can be O(n) in worst case. So better to use Fenwick tree or segment tree.
Let's outline algorithm:
-
Compute prefix sums: prefix[0] = 0, then for i from 1 to n: prefix[i] = prefix[i-1] + nums[i-1].
-
We need to consider all prefix sums as well as prefix[i] - lower and prefix[i] - upper for each i for queries. To use Fenwick tree, we compress all these values into sorted unique list.
Let set = all prefix[i] for i=0..n, plus all (prefix[i] - lower) and (prefix[i] - upper) for i=0..n. Then sort and unique to get mapping value -> index.
-
Initialize Fenwick tree (size = number of unique values). Initially, we will add prefix[0] (which is 0) to Fenwick tree before iterating i from 1 to n? Actually we need to include prefix[0] as a previous prefix sum for subarrays starting at index 1. So we start with fenwick.add(compressed_index_of(prefix[0]), 1).
-
For i from 1 to n:
- Compute current prefix = prefix[i].
- Compute low_val = prefix - upper (because we want S[j] >= S[i] - upper) Actually condition: lower <= prefix - S[j] <= upper => S[j] >= prefix - upper and S[j] <= prefix - lower.
So lower bound = prefix - upper, upper bound = prefix - lower.
- Query fenwick for count of values in [low_val, upper_val] (inclusive). Use fenwick.range_sum(compressed(low_val), compressed(upper_val)).
- Add that count to answer.
- Then add current prefix to fenwick: fenwick.add(compressed(prefix), 1).
-
Return answer.
Note: The compression must map the actual values to indices 1..m.
We must ensure that low_val and upper_val are present in compression. That's why we added them to the set.
Complexity: O(n log n) for prefix sum, O(n log n) for Fenwick operations, O(n log n) for compression sorting.
Edge cases: large numbers, negative numbers, overflow? Use long long for prefix sums because nums can be large (maybe up to 10^9 and n up to 10^5). So prefix sum may be up to 10^14, use long long.
Implement Fenwick tree:
class Fenwick {
vector bit; // or long long for counts? counts up to n, so int fine but use long long for answer.
int n;
Fenwick(int n): n(n), bit(n+1,0) {}
void add(int idx, int delta) {
for(; idx <= n; idx += idx & -idx) bit[idx] += delta;
}
long long sum(int idx) { // prefix sum from 1 to idx
long long res = 0;
for(; idx > 0; idx -= idx & -idx) res += bit[idx];
return res;
}
long long range_sum(int l, int r) {
if(l > r) return 0;
return sum(r) - sum(l-1);
}
};
But careful: Since we compress values to indices, we need to map value to index. Use unordered_map? Or binary search on sorted vector. We'll have vector allVals sorted. Then for a given value, use lower_bound to get index+1? Actually we want 1-indexed for Fenwick. So we can store mapping: map from value to index (1-indexed). Use unordered_map? But we have up to 3n+1 values (maybe 300k). We can sort and then use binary search each time: O(log n) per query, which is fine. But we could also precompute an array of values and use lower_bound each time we need to get index. That's O(log n) extra, overall O(n log n) still. But we are already doing O(log n) for fenwick operations, so overall O(n log n) but with extra factor. Could also store a map from value to compressed index after building: unordered_map<long long, int> idxMap; but careful with long long keys, but okay. We'll do that for simplicity.
Steps:
- Build vector allVals; push all prefixes (prefix[i]) and also prefix[i] - lower and prefix[i] - upper for each i.
- Sort allVals, unique.
- Create unordered_map<long long, int> comp; for (int i=0; i<allVals.size(); i++) comp[allVals[i]] = i+1; (1-indexed)
- Then fenwick size = allVals.size().
But we need to ensure that when we query for low_val and upper_val, they exist in comp. Since we added them, they should exist. But careful: after sorting and unique, maybe some duplicates? That's fine, comp will map to the single index. But we need to use the same index for both low and high. However, if low_val is not exactly present? We added them to set, so they will be present. But due to integer arithmetic, prefix[i]-lower and prefix[i]-upper are exactly computed, so they will be in allVals. So they will be present. However, after unique, we have one copy. So lower_bound not needed; we can directly map using comp.
But careful: In Fenwick, we need to query range sum between compressed(low_val) and compressed(upper_val). Since we have exact indices, that's fine. But what if low_val > upper_val? That can happen if prefix - upper > prefix - lower? Actually lower <= upper, so prefix - upper <= prefix - lower. So low <= upper. So valid.
But also if the range is empty because there is no prefix sum in that range, query returns 0.
Thus algorithm works.
Complexities: O(n log n) time, O(n) space.
Edge: If n = 0? Then prefix array has only 0, but we will not iterate i from 1 to n (n=0, loop not run). But we still have prefix[0]=0 in fenwick, but we count subarrays? For empty array, no subarray, answer=0. But if n=0, our code would compute prefix array size 1, fenwick initialized with prefix[0] and then no loop, answer remains 0. That's correct.
Let's test with example: nums = [-2,5,-1], lower=-2, upper=2. Expected subarrays: [-2] sum=-2 in range? yes (lower=-2) so count; [5] sum=5 no; [-1] sum=-1 yes; [-2,5]=3 no; [5,-1]=4 no; [-2,5,-1]=2 yes. So total 3? Actually also [-2,5,-1] sum=2, that's 1; [-2] sum=-2, that's 1; [-1] sum=-1, that's 1; also maybe [ -2,5] sum=3 no; [5,-1] sum=4 no; So total 3. Another known solution: count of range sum.
We can simulate: prefix: [0, -2, 3, 2]. i=1: prefix=-2, low_val=-2 - upper? upper=2 => low = -2-2=-4, high = -2 - (-2)=0. Query fenwick for S[j] in [-4,0]. We have only prefix[0]=0, which is in range => count +=1. Then add -2. i=2: prefix=3, low=3-2=1, high=3-(-2)=5. Query for S[j] in [1,5]. Existing prefix sums: 0, -2 => none => 0. Add 3. i=3: prefix=2, low=2-2=0, high=2-(-2)=4. Query for S[j] in [0,4]. Existing: 0, -2, 3. 0 and 3 are in range => count+=2. Answer=1+0+2=3. Correct.
Now code.
We'll implement in C++? The problem says "write a function", not language specific. Usually in interview we can choose language. I'll implement in C++ or Python? Since it's about algorithm explanation, maybe Python is easier. But we need to be careful about performance for large n? In Python, Fenwick tree with O(n log n) is fine for up to 10^5. We'll write in Python.
Let's implement solve function:
def countRangeSum(nums: List[int], lower: int, upper: int) -> int:
Implementation details:
- Use from typing import List.
- Compute prefix sums using list of long ints.
- Build allVals = set; for each p in prefix: add p, p - lower, p - upper. Then convert to sorted list.
- Create dict mapping value to index (1-indexed).
- Fenwick class.
- fen = Fenwick(len(allVals))
- ans = 0
- fen.add(comp[prefix[0]], 1)
- For i in range(1, len(prefix)):
p = prefix[i]
low_val = p - upper
high_val = p - lower
low_idx = comp[low_val]
high_idx = comp[high_val]
ans += fen.range_sum(low_idx, high_idx)
fen.add(comp[p], 1)
- return ans
Potential issue: The comp mapping for low_val and high_val: if low_val or high_val are not exactly in comp? We added them to allVals, but after sorting and unique, they are present. However, due to the fact that prefix[i] - lower and prefix[i] - upper may be duplicates among themselves or with prefix sums, but they are still included. So they will be in the list, but we must ensure they are included exactly as we added them. That is guaranteed because we added all to a set then sorted. But careful: when we add to a set, we add each value exactly once. However, we must add them for each i, but set automatically deduplicates. That's fine.
Alternative: Use bisect on sorted allVals to get index, but we can store mapping.
But what about low_val > high_val? Actually lower <= upper so low_val <= high_val. So fine.
One more detail: In Fenwick range_sum, we need to handle when low_idx > high_idx? Not possible.
Testing: With small example, it works.
Let's consider large numbers: Use Python's int, which is arbitrary precision, but okay.
Time complexity: O(n log n) with about 3n values, sorting O(n log n), Fenwick operations O(n log m) where m ~ 3n.
We must also consider that if we use a dict for comp, we need to make sure we use same representation; long integers as keys okay.
Alternatively, we could use bisect without dict: compute low_idx = bisect_left(allVals, low_val) + 1? But we need to ensure the value exists. Since we added low_val, we can get idx via bisect_left(allVals, low_val) which will give the exact position because it's in the list. But due to duplicates? allVals sorted unique, so if low_val present, bisect_left returns its index. That yields 0-based, add 1 for fenwick. That is simpler and avoids dict. Similarly for high_val? But we need to get the index for the value exactly. If high_val is in allVals, bisect_left gives index. But what if high_val is not present? It should be present because we added it. But careful: due to integer arithmetic, if we add allVals from prefix and p-lower and p-upper, they are exactly the numbers we compute for low_val and high_val. So they must be present. However, what if p-lower is not exactly the same as a value in allVals because of rounding? No, it's exact. So it's present. But when we do bisect_left, it returns the first index where that value could be inserted. If value is present, it returns the index of that value. So okay.
But we must be careful: after sorting allVals, we need to make it a list. For each query, we need to find index. That would be O(log m) each, same as dict O(1) average. Using bisect is simpler.
Let's implement using bisect. However, note that we need to also get index for prefix p when adding; we also need to get index for p. That we can also get via bisect. So we can avoid building a dict.
But we should also include prefix[0] initially, we need its index.
Implementation:
allVals = []
for p in prefix:
allVals.append(p)
allVals.append(p - lower)
allVals.append(p - upper)
sorted_vals = sorted(set(allVals))
Then define a function to get index:
def get_index(val):
return bisect.bisect_left(sorted_vals, val) + 1
Because sorted_vals is sorted list. Since val is guaranteed to be in sorted_vals (we added all), bisect_left will find it.
But careful: What if val is not present? Because we used set(allVals) which contains all values we added. So it should be present. But due to floating point? No integers. So okay.
But one more nuance: When we sort set, we might lose duplicates; but that's fine.
Now, we need to be cautious: bisect_left returns 0-based index. Fenwick tree indices start at 1. So add 1.
Now, for each i, we compute low_idx = get_index(p - upper), high_idx = get_index(p - lower). Then query range sum between low_idx and high_idx inclusive.
But note: In Fenwick tree, we need to handle that high_idx >= low_idx always. Since p - upper <= p - lower, and indices reflect order, so high_idx >= low_idx because sorted_vals preserves order.
Edge: If lower == upper, then low_idx == high_idx. That's fine.
Now implement Fenwick.
Fenwick: We'll store bit array of size len(sorted_vals)+1 (1-indexed). For adding and summing.
But careful: The range of indices: 1 to size. So we need to allocate size+1.
Let's code:
class Fenwick:
def init(self, size):
self.n = size
self.bit = [0]*(self.n+1)
def add(self, idx, delta):
while idx <= self.n:
self.bit[idx] += delta
idx += idx & -idx
def sum(self, idx):
s = 0
while idx > 0:
s += self.bit[idx]
idx -= idx & -idx
return s
def range_sum(self, l, r):
if l > r:
return 0
return self.sum(r) - self.sum(l-1)
Now algorithm:
def countRangeSum(nums, lower, upper):
n = len(nums)
prefix = [0]*(n+1)
for i in range(1,n+1):
prefix[i] = prefix[i-1] + nums[i-1]
allVals = []
for p in prefix:
allVals.append(p)
allVals.append(p - lower)
allVals.append(p - upper)
sorted_vals = sorted(set(allVals))
size = len(sorted_vals)
fen = Fenwick(size)
# helper
import bisect
def get_idx(val):
# binary search to find index (1-indexed)
return bisect.bisect_left(sorted_vals, val) + 1
ans = 0
# insert prefix[0]
fen.add(get_idx(prefix[0]), 1)
for i in range(1, n+1):
p = prefix[i]
low_val = p - upper
high_val = p - lower
low_idx = get_idx(low_val)
high_idx = get_idx(high_val)
ans += fen.range_sum(low_idx, high_idx)
fen.add(get_idx(p), 1)
return ans
We need to ensure that get_idx returns correct index. Since sorted_vals contains the values, bisect_left gives index. But what about duplicates? Since we used set, sorted_vals has unique values. For values that appear multiple times, bisect_left returns the first occurrence. That's fine.
Now test with example: nums = [-2,5,-1], lower=-2, upper=2. Compute prefix: [0, -2, 3, 2]. allVals: for p=0: add 0, 0-(-2)=2? Actually p - lower: 0 - (-2)=2, p - upper: 0 - 2 = -2. So add 0,2,-2. For p=-2: add -2, -2-(-2)=0, -2-2=-4. So values: -2,0,-4. For p=3: 3, 3-(-2)=5, 3-2=1. So 3,5,1. For p=2: 2, 2-(-2)=4, 2-2=0. So 2,4,0. Combine set: [-4,-2,0,1,2,3,4,5] sorted. get_idx(0)=? sorted_vals index: -4(0), -2(1),0(2),1(3),2(4),3(5),4(6),5(7) 0-based. So get_idx(0)=3? Actually 0-based 2 -> +1 =3. Okay.
Now process:
fen.add(get_idx(0)=3, 1).
i=1 p=-2. low_val = -2 - upper? upper=2 => -2-2=-4. high_val = -2 - lower? lower=-2 => -2 - (-2)=0. low_idx = get_idx(-4) = 0-based0->1, high_idx = get_idx(0)=3. range_sum(1,3) = fen.sum(3)-fen.sum(0). fen.sum(3): includes index 1? fen currently only index 3=1, so sum(3) = 1 (since we added at idx3). sum(0)=0. So range_sum=1. ans=1. Then fen.add(get_idx(-2)). -2 index: get_idx(-2)=2 (0-based1->2). fen.add(2,1). So now fen has counts at 2 and 3.
i=2 p=3. low_val=3-2=1, high_val=3-(-2)=5. low_idx = get_idx(1)=4 (0-based3->4). high_idx = get_idx(5)=8 (0-based7->8). range_sum(4,8): sum(8)-sum(3). Fen currently has at idx2 and idx3. sum(8) = sum up to 8 includes idx2 and idx3 ->2. sum(3) = sum up to 3 includes idx2 and idx3? idx3 is 3, sum(3) includes idx2? idx2 <=3, idx3=3 <=3, so sum(3)=2. So range_sum = 0. ans=1. Then fen.add(get_idx(3)=6? Actually sorted_vals: 0:-4,1:-2,2:0,3:1,4:2,5:3,6:4,7:5. get_idx(3)=5? Wait index of 3 is 5 (0-based5). +1 =6. So add at idx6.
i=3 p=2. low_val=2-2=0, high_val=2-(-2)=4. low_idx = get_idx(0)=3, high_idx = get_idx(4)=7? sorted_vals[6]=4 -> idx=7. range_sum(3,7) = sum(7)-sum(2). sum(7): includes indices: we have added idx3 (prefix0), idx2 (prefix -2), idx6 (prefix3). idx3=3? Actually we added at idx3 for prefix0, idx2 for -2, idx6 for 3. sum(7) counts all <=7: includes idx2,3,6 => 3. sum(2) includes indices <=2: idx2 only? idx2 is 2, so sum(2)=1. So range_sum=2. ans=3. Add prefix2 at get_idx(2)=5? sorted_vals index of 2 is 4 (0-based) -> +1=5. Add.
So ans=3. Works.
Edge case: all negative numbers? Should be fine.
Potential overflow: answer can be up to n*(n+1)/2, which for n=10^5 is ~5e9, fits in 64-bit. Use Python int.
Now explanation: We'll provide algorithm description.
But the problem statement: "You are given an array of integers nums. Write a function to find the number of subarrays that have a sum within a given range [lower, upper]. Please write a function that solves this problem, and explain your algorithm." So we need to produce code and explanation. We can choose any language. I'll provide Python code.
We should also discuss alternative methods: O(n^2) brute force, then optimized O(n log n) using prefix sums and Fenwick tree.
Let's provide full solution.
Also note: We can use a balanced BST with order statistics (like SortedList from sortedcontainers) but Fenwick tree is good.
I'll produce final answer with code and explanation.
But also ensure we handle large inputs. Use sys.setrecursionlimit? Not needed.
Now write the solution.
Potential improvements: Instead of three values per prefix, we can compress only prefix sums, and then for each query we need to find the number of prefix sums in range [p-upper, p-lower]. Since we have sorted list of prefix sums only, we could use binary search to find the count of already processed prefix sums within that range. But that would be O(n^2) if we use linear scanning of sorted list? Actually if we maintain a sorted list of processed prefix sums and for each p we do binary search to find the range of indices and then need count of elements in that range. If we use a data structure like a balanced BST with subtree sizes, we can query count in range. But that's essentially an order statistic tree. Fenwick tree is simpler after compression of all possible values. So okay.
Now finalize.
Let's also consider memory: sorted_vals size <= 3n+1 ~ 300k, Fenwick bit array size 300k+1, fine.
Now produce answer with code and explanation.
Will also include test case.
We might also mention that we can use a segment tree, but Fenwick is simpler.
I'll produce final.
We need to count the number of contiguous subarrays of nums whose sum lies in the inclusive interval [lower, upper].
1. Prefix Sums and the Condition
Let pref[i] be the sum of the first i elements (pref[0] = 0).
The sum of subarray nums[l … r] (0‑based, l ≤ r) equals pref[r+1] – pref[l].
We want:
lower ≤ pref[r+1] – pref[l] ≤ upper
⇔ pref[r+1] – upper ≤ pref[l] ≤ pref[r+1] – lower
For a fixed right end r (i.e., for p = pref[r+1]) we must count previously seen prefix sums pref[l] (with l ≤ r) that lie in [p - upper, p - lower].
Thus we need a data structure that supports:
- insert a prefix sum,
- query how many stored values are inside a given interval.
Both operations must be O(log n) to achieve an overall O(n log n) solution.
2. Coordinate Compression
The prefix sums and the query boundaries (p - lower, p - upper) can be arbitrary 64‑bit integers.
We compress all values that will ever appear to a small range of indices [1 … M]:
values = { pref[i] } ∪ { pref[i] - lower } ∪ { pref[i] - upper } for all i
Sort the unique values and assign each a 1‑based index. After compression every value can be looked up in O(log M) by binary search (or saved in a map).
3. Fenwick Tree (Binary Indexed Tree)
A Fenwick tree maintains an array bit[1..M] where bit[i] stores the count of values whose compressed index is i.
add(idx, 1) – inserts a value.
range_sum(l, r) = sum(r) – sum(l-1) – returns how many stored values have indices in [l, r].
Both operations are O(log M).
4. Algorithm
pref[0] = 0
for i = 1..n: pref[i] = pref[i-1] + nums[i-1]
compress all needed values → sorted_vals, size = M
fen = Fenwick(M)
answer = 0
fen.add( index(pref[0]), 1 ) // pref[0] is available for subarrays starting at index 0
for i = 1..n:
p = pref[i]
low = p - upper
high = p - lower
L = index(low) // compressed index of low
R = index(high) // compressed index of high
answer += fen.range_sum(L, R)
fen.add( index(p), 1 ) // make this prefix available for future positions
return answer
The loop visits each prefix once, performs two binary searches (index), one range query, and one update – all O(log n). Total time O(n log n). Memory O(n).
5. Correctness Proof
We prove that the algorithm returns exactly the number of subarrays with sum in [lower, upper].
Lemma 1
For any r (0 ≤ r < n) the number of subarrays ending at r with sum in [lower, upper] equals the number of indices l (0 ≤ l ≤ r) such that pref[l] lies in [pref[r+1] – upper, pref[r+1] – lower].
Proof. The sum of nums[l … r] is pref[r+1] – pref[l]. The inequality lower ≤ pref[r+1] – pref[l] ≤ upper is equivalent to pref[r+1] – upper ≤ pref[l] ≤ pref[r+1] – lower. ∎
Lemma 2
At the moment the algorithm processes pref[i] (i.e., right end r = i-1), the Fenwick tree contains exactly the values pref[0] … pref[i-1].
Proof. Initially the tree contains only pref[0]. After handling each i, we insert pref[i]. By induction, before processing pref[i] the tree holds pref[0] … pref[i-1]. ∎
Lemma 3
During iteration i the algorithm adds to answer precisely the number of subarrays ending at r = i-1 whose sums lie in [lower, upper].
Proof. By Lemma 2 the tree stores all pref[l] for l ≤ i-1. The query range_sum(L,R) counts those stored values with indices between L and R, i.e., all pref[l] such that pref[l] ∈ [pref[i] – upper, pref[i] – lower]. By Lemma 1 this count equals the number of qualifying subarrays ending at r = i-1. ∎
Theorem
After the loop finishes, answer equals the total number of subarrays of nums whose sum is in [lower, upper].
Proof. Every subarray has a unique right end r. The algorithm, during iteration i = r+1, counts exactly those subarrays ending at r that satisfy the condition (Lemma 3). Summing over all i = 1 … n counts every valid subarray exactly once. ∎
6. Complexity Analysis
Time:
- Prefix sums:
O(n)
- Building and sorting the compression list:
O(n log n)
- Each of the
n iterations: two binary searches (O(log n)), one Fenwick range query (O(log n)), one Fenwick update (O(log n)). Overall O(n log n).
Space:
- Prefix array:
O(n)
- Compression list: at most
3n+1 values → O(n)
- Fenwick tree:
O(n)
Total O(n) extra space.
7. Reference Implementation (Python)
from typing import List
import bisect
class Fenwick:
"""Fenwick Tree for prefix sums of frequencies."""
def __init__(self, size: int):
self.n = size
self.bit = [0] * (self.n + 1)
def add(self, idx: int, delta: int = 1) -> None:
"""Increase position idx by delta (idx is 1‑based)."""
while idx <= self.n:
self.bit[idx] += delta
idx += idx & -idx
def sum(self, idx: int) -> int:
"""Prefix sum from 1 to idx (inclusive)."""
s = 0
while idx > 0:
s += self.bit[idx]
idx -= idx & -idx
return s
def range_sum(self, l: int, r: int) -> int:
"""Sum of frequencies in [l, r] (1‑based, inclusive)."""
if l > r:
return 0
return self.sum(r) - self.sum(l - 1)
def countRangeSum(nums: List[int], lower: int, upper: int) -> int:
"""
Returns the number of subarrays whose sum is within [lower, upper].
"""
n = len(nums)
# Compute prefix sums
pref = [0] * (n + 1)
for i in range(1, n + 1):
pref[i] = pref[i - 1] + nums[i - 1]
# Collect all values that will appear in queries or updates
all_vals = []
for p in pref:
all_vals.append(p)
all_vals.append(p - lower)
all_vals.append(p - upper)
# Coordinate compression
sorted_vals = sorted(set(all_vals))
m = len(sorted_vals)
# Helper: get 1‑based compressed index of a value (value is guaranteed to be in sorted_vals)
def get_idx(val):
# bisect_left returns 0‑based position; add 1 for Fenwick's 1‑based indexing
return bisect.bisect_left(sorted_vals, val) + 1
fen = Fenwick(m)
answer = 0
# Insert pref[0]
fen.add(get_idx(pref[0]), 1)
# Process each prefix from 1..n
for i in range(1, n + 1):
p = pref[i]
low_val = p - upper
high_val = p - lower
L = get_idx(low_val)
R = get_idx(high_val)
answer += fen.range_sum(L, R)
fen.add(get_idx(p), 1)
return answer
Example
>>> countRangeSum([-2, 5, -1], -2, 2)
3
The three subarrays are [-2], [-1], and [-2,5,-1]. The algorithm runs in O(n log n) time and O(n) space.