You are given an array of integers nums. Write a function to find the number of subarrays that have a sum less than a given value k. Please write a function that solves this problem, and explain your algorithm.
Assistant
We need to write a function that counts subarrays with sum less than k. Input: array of integers nums, integer k. We need to return count of subarrays whose sum is < k.
We need to design an algorithm. Possibly O(n log n) using prefix sums and a Fenwick tree or balanced BST, or O(n^2) naive. But likely we need efficient solution. Since constraints not given, we can propose O(n log n) using prefix sums and order-statistic tree. Or O(n) using sliding window? But sliding window works for non-negative numbers only. If nums can have negative numbers, then sliding window fails. The problem statement doesn't specify if nums are non-negative. Typically, "subarray sum less than k" with possibly negative numbers is solved with prefix sums and some data structure to count pairs (i, j) where prefix[j] - prefix[i] < k => prefix[i] > prefix[j] - k? Actually we need count of i<j such that sum_{i}^{j-1} < k. Using prefix sums P[0]=0, P[1]=nums[0], ..., P[n]=sum up to n-1. Then subarray from i to j-1 (i from 0 to n-1, j from i+1 to n) sum = P[j] - P[i]. Condition: P[j] - P[i] < k => P[i] > P[j] - k? Actually P[i] <=? Let's rearrange: P[j] - P[i] < k => P[i] > P[j] - k. But careful: this inequality direction: P[j] - P[i] < k => -P[i] < k - P[j] => multiply by -1 flips: P[i] > P[j] - k. Yes. So for each j, we need count of i < j such that P[i] > P[j] - k.
Alternatively, we can count i such that P[i] <= P[j] - k and subtract from j (number of i's). Actually we want P[i] > P[j] - k, so number of i's with i<j and P[i] > P[j]-k. That's total i count (j) minus number of i with P[i] <= P[j] - k. So we can compute for each j, how many previous prefix sums are <= P[j] - k. That's typical problem "count of subarray sums less than k" which is known as "subarray sum less than K" (Leetcode 862? Actually Leetcode 862 is "Shortest Subarray with Sum at Least K", but counting subarrays with sum less than K is less common but similar). There's also "count number of subarrays with sum less than K" for negatives, solution using prefix sums and BIT after coordinate compression.
Thus algorithm: compute prefix sums array P[0..n]. Use a balanced BST or Fenwick tree to maintain counts of prefix sums seen so far (starting with P[0]=0). For each j from 1 to n, we query how many prefix sums among indices 0..j-1 are <= P[j] - k? Actually we want count of i such that P[i] > P[j] - k. So count_i = j - count_{P[i] <= P[j]-k}. So we can query the number of prefix sums <= (P[j] - k) from the data structure. Then add to total: j - that count. Then insert P[j] into the data structure.
But careful: For j, i ranges from 0 to j-1. So there are j previous prefix sums (including P[0]). So total possible i is j. So number of i with P[i] > P[j] - k = j - (# of i with P[i] <= P[j] - k). That works.
But we need to ensure that we count subarrays with sum exactly less than k, not less than or equal. Condition is < k, so P[j] - P[i] < k => P[i] > P[j] - k. If we use query for <= P[j] - k, then we count those that are <= P[j] - k. But careful: Suppose P[i] = P[j] - k exactly. Then sum = k, not less than k. So we need to exclude those. So count of i with P[i] > P[j] - k includes those strictly greater, so those <= P[j] - k are not counted. So j - count_{<=} works because those > are desired. But what about P[i] = P[j] - k? Those are not counted (since we subtract count_{<=} includes them). That's correct. So using <= is fine.
But we need to ensure that for negative numbers, prefix sums can be large negative. So we need to coordinate compress prefix sums and also the query thresholds P[j] - k. We'll need to query "number of prefix sums <= X" for various X. So we can compress all prefix sums and all (P[j] - k) values? Actually we need to map each P[j] and P[j]-k to integers for Fenwick tree. Since we query on P[j] - k which may not be exactly a prefix sum. So we need to include all unique values that appear in P and also all (P[j] - k). Or we can use a balanced BST (like C++ multiset) that can count number of elements <= X in O(log n) with order statistics tree (policy based data structure). In Python, we can use sorted list with bisect, but insertion O(n). Better use Fenwick or segment tree with compression.
So algorithm steps:
Compute prefix sum array: P[0] = 0; for i from 1 to n: P[i] = P[i-1] + nums[i-1].
Create list of all values that need to be considered: all P[i] for i=0..n, and all (P[i] - k) for i=1..n? Actually we need to query for each j (1..n) the threshold T = P[j] - k. Also we need to store P[j] for insertion. So we can compress all these values: set = all P[i] plus all (P[i] - k) for i=1..n. But note we only query thresholds before inserting P[j]? Actually process j sequentially: before processing j, we have inserted P[0..j-1] into structure. So we need to query threshold T = P[j] - k. That threshold may be any number. To get index for Fenwick, we need to map T to a position in sorted list of possible values. But we only need to query count of inserted values <= T. So we need to be able to find the index of T in the compressed coordinate. We could sort all possible values (including all P and all (P - k)), then do binary search to get the index for T. However, note that we may have thresholds that are not exactly any prefix sum; we need to find the largest index such that value <= T. Since our Fenwick tree indices correspond to sorted unique values, we can do coordinate compression: create sorted list of unique values from the set S = { all P[i] } ∪ { all P[i] - k }. Then for each T, we find its rank by binary searching in that sorted list. But we need to treat the Fenwick tree such that it can count values with actual value <= T. Since T may not be exactly in S, we need to find the index of the largest element in S <= T. That's simply bisect_right(S, T) - 1 gives position. But if we compress by assigning each distinct value an index from 1..m, then we can query prefix sum up to that index. But we need to ensure that we consider values between compressed points: since our values are only those in S, any T that lies between two compressed values will map to the lower one's index. But that's fine because we only have inserted values that are in S. For query, we want count of inserted values with value <= T. Since all inserted values are in S, we can find the largest compressed value <= T, and query up to that index. That's correct. So we need to compress S, and for each T compute idx = bisect_right(compressed, T) (gives first index > T, then we query fenwick up to idx-1). Or we can compute idx = bisect_left(compressed, T+1) maybe easier.
Alternatively, we can use a balanced BST (like sortedcontainers in Python) if allowed. Since we are writing a function in generic language, we can propose an O(n log n) solution using a sorted list and binary search with insertion using bisect.insort, but that is O(n^2). So for efficiency, Fenwick is better.
Let's design with Fenwick tree (Binary Indexed Tree). Steps:
Compute all prefix sums P[0..n].
Create list vals = set()
For each p in P: add p.
For each j from 1..n: add P[j] - k.
Convert to sorted list: sorted_vals = sorted(vals).
Define mapping: val_to_idx = {v: i+1 for i, v in enumerate(sorted_vals)}. Fenwick uses 1-indexing.
Initialize BIT with size = len(sorted_vals).
Initially, we need to "insert" P[0] (which is 0). So update BIT at idx0 = val_to_idx[0] with +1.
total_count = 0
For j from 1 to n:
T = P[j] - k
find index of largest value <= T
idx = bisect_right(sorted_vals, T) # returns position where T would be inserted to keep order, i.e., all indices < idx have value <= T.
So if idx == 0, no values <= T.
count_le = BIT.query(idx) # query prefix sum up to idx (if BIT is 1-indexed and sorted_vals indices are 1..m; but bisect_right returns 0-based index, so we need to query BIT up to idx because BIT indices shift by 1? Let's think.)
Actually, if sorted_vals is 0-indexed, and we map values to index = position+1. For query, we want sum of counts for all values with compressed index <= idx (where idx = number of values <= T). Since compressed indices are 1..m, and there are exactly idx values in sorted_vals[0:idx] (i.e., up to index idx-1). So we should query BIT at position idx (since BIT is 1-indexed and we added at index = position+1). For value v, its index = pos+1 where pos = index in sorted_vals (0-based). When we compute idx = bisect_right(sorted_vals, T), that gives number of values <= T. That count corresponds to the last position's index = idx (since positions are 0..idx-1). So the BIT query should be at idx. But careful: if idx=0, we want query(0) which returns 0. BIT query should handle that.
Then number of i with P[i] > P[j] - k = j - count_le. Because before processing j, we have inserted j prefix sums (P[0]..P[j-1]). So total i = j. So good.
total_count += (j - count_le)
Then insert current prefix sum P[j] into BIT: idx_ins = val_to_idx[P[j]]; BIT.update(idx_ins, 1)
Return total_count.
Complexity: O(n log n).
We need to be careful with integer overflow? Python ints fine.
Edge cases: empty array? Then n=0, we need to return 0. Our loop from 1 to n won't run; total_count=0.
Now we need to write the function. Also explain algorithm.
We should provide the code in Python. We'll implement Fenwick tree as class.
But maybe there is an O(n) solution if all numbers non-negative. The problem statement says "array of integers", so may include negatives. We'll go with the general solution.
Alternatively, we can use merge sort based counting similar to counting inversions? There is a known method: using divide and conquer to count pairs (i<j) such that P[j] - P[i] < k. That's like counting pairs with difference less than k. That can be done in O(n log n) with a two-pointer after sorting prefix sums? Actually for counting pairs with difference less than k where i<j and we want P[j] - P[i] < k? But careful: P[j] - P[i] is sum of subarray i..j-1. That's similar to counting pairs (i, j) with i<j and P[i] > P[j] - k? Not symmetric. Could be done with mergesort? Possibly but BIT is simpler.
We'll go with BIT.
Now write the solution.
We'll structure:
def count_subarrays_sum_less_than_k(nums, k):
n = len(nums)
prefix = [0]*(n+1)
for i in range(1, n+1):
prefix[i] = prefix[i-1] + nums[i-1]
code
# collect values for compression
vals = set()
for p in prefix:
vals.add(p)
for j in range(1, n+1):
vals.add(prefix[j] - k)
sorted_vals = sorted(vals)
# mapping
val_to_idx = {v: i+1 for i, v in enumerate(sorted_vals)}
size = len(sorted_vals)
# Fenwick tree
class Fenwick:
def __init__(self, n):
self.n = n
self.tree = [0]*(n+1)
def update(self, i, delta):
while i <= self.n:
self.tree[i] += delta
i += i & -i
def query(self, i):
# sum from 1..i
s = 0
while i > 0:
s += self.tree[i]
i -= i & -i
return s
bit = Fenwick(size)
# insert prefix[0] = 0
bit.update(val_to_idx[0], 1)
total = 0
for j in range(1, n+1):
T = prefix[j] - k
# find index of largest value <= T
idx = bisect.bisect_right(sorted_vals, T) # number of values <= T
count_le = bit.query(idx) # query up to idx
total += j - count_le
# insert prefix[j]
bit.update(val_to_idx[prefix[j]], 1)
return total
Need to import bisect.
Test with some examples.
Example: nums = [1, 2, 3], k=4. Subarrays: [1]=1 (<4), [2]=2 (<4), [3]=3 (<4), [1,2]=3 (<4), [2,3]=5 (!=), [1,2,3]=6 (!=). So count=4. Let's compute: prefix = [0,1,3,6]. vals include 0,1,3,6, and each prefix[j]-k: for j=1:1-4=-3; j=2:3-4=-1; j=3:6-4=2. So set: {0,1,3,6,-3,-1,2}. sorted: [-3,-1,0,1,2,3,6]. mapping: -3->1,-1->2,0->3,1->4,2->5,3->6,6->7. Initialize bit size 7. Insert prefix[0]=0 at idx=3. j=1: T = -3, idx = bisect_right([-3,-1,0,1,2,3,6], -3) = 1 (since -3 <= -3, next is -1 > -3, so count of <= -3 is 1). query(1) = ? We have inserted only 0 at idx=3. So bit.query(1)=0. total += 1-0 =1. Insert prefix[1]=1 at idx=4. j=2: T= -1, idx = bisect_right([-3,-1,0,1,2,3,6], -1)=2. query(2)=? inserted: idx3 and idx4. query(2) sums indices 1..2, none, so 0. total +=2-0=2 => total 3. Insert prefix[2]=3 at idx=6. j=3: T=2, idx=bisect_right(...,2)=5? sorted: [-3,-1,0,1,2,3,6]; values <=2: -3,-1,0,1,2 => 5 values. So idx=5. query(5) gives counts of inserted values with index <=5. Inserted: idx3 (0), idx4 (1), idx6 (3). idx6 >5 so not counted. So count_le = 2? Actually only indices <=5: we have idx3 and idx4 => that's 2. total += 3-2 =1 => total=4. Works.
Edge with negative numbers: nums = [-1, -2, 3], k=2. Subarrays: [-1] sum=-1<2, [-2]=-2<2, [3]=3>2, [-1,-2]=-3<2, [-2,3]=1<2, [-1,-2,3]=0<2. So all except [3] count=5. Let's compute: n=3, prefix: [0, -1, -3, 0]. vals: prefix:0,-1,-3,0; plus prefix[j]-k: j=1: -1-2=-3, j=2: -3-2=-5, j=3:0-2=-2. So set: {0,-1,-3,-5,-2}. sort: [-5,-3,-2,-1,0]. mapping: -5->1, -3->2, -2->3, -1->4, 0->5. Insert prefix[0]=0 at idx=5. j=1: T = -3, idx = bisect_right([-5,-3,-2,-1,0], -3)=2? values <= -3: -5,-3 =>2. query(2)=? inserted: idx5 (0) not counted =>0. total +=1-0=1. Insert prefix[1]=-1 at idx=4. j=2: T = -5, idx = bisect_right(...,-5)=1. query(1)=0. total +=2-0=2 => total 3. Insert prefix[2]=-3 at idx=2. j=3: T = -2, idx = bisect_right(...,-2)=3? values <=-2: -5,-3,-2 =>3. query(3) counts indices 1..3. Inserted so far: idx5, idx4, idx2. idx2 is 2, idx4=4>3 not counted, idx5>3 not counted. So count_le = 1 (since idx2 <=3). Actually query(3) includes idx1 and idx2. We have inserted at idx2=2 (value -3) count 1. So count_le=1. total +=3-1=2 => total 5. Correct.
Edge with k negative? Possibly. Should work.
So algorithm ok.
Now we need to write explanation.
Also note that we can use "sorted list" if n is small, but we provide efficient.
We'll write code with necessary imports and function.
Potential improvements: In Python, we can use bisect module and a Fenwick class.
We'll also mention that we use coordinate compression because prefix sums can be large.
Alternative approach using balanced BST (like sortedcontainers) but we stick to BIT.
Now craft final answer: Provide code and explanation.
We'll also mention time O(n log n), space O(n).
Let's produce final output.
Solution Explanation
We are given an array nums and an integer k.
We need the number of contiguous subarrays whose sum is strictly less than k.
The sum of the subarray nums[l … r] (0 ≤ l ≤ r < n) equals
code
sum(l, r) = P[r+1] – P[l]
We require
code
P[r+1] – P[l] < k ⇔ P[l] > P[r+1] – k (1)
For a fixed right endpoint j = r+1 (so j runs from 1 to n) we need to count
how many indices i (0 ≤ i < j) satisfy P[i] > P[j] – k.
If we already know how many previous prefix sums are ≤ P[j] – k,
the answer for this j is
code
good(j) = j – (# of i with P[i] ≤ P[j] – k)
Summing good(j) for all j gives the required answer.
Thus the problem reduces to maintaining a multiset of already‑seen prefix sums
and, for each new prefix, answering “how many are ≤ X?”.
Both operations need to be fast → O(log n) each.
2. Data structure: Fenwick Tree (Binary Indexed Tree)
A Fenwick tree stores frequencies of values and can return the prefix sum
(∑_{value ≤ x} frequency) in O(log M), where M is the number of distinct
values.
The values we ever encounter are the prefix sums themselves and the query
thresholds P[j] – k. To use a Fenwick tree we compress all these numbers into
a small index range.
Coordinate compression
code
values = { all P[i] for i = 0..n } ∪ { P[j] – k for j = 1..n }
sorted_vals = sorted(values) # length = M
each original number v → index = position in sorted_vals + 1 (1‑based)
Now “how many inserted prefix sums ≤ X?” becomes a Fenwick query up to the
compressed index of X. If X is not exactly in sorted_vals we take the
largest value ≤ X; equivalently we can use bisect_right to get the count of
compressed values ≤ X.
3. Algorithm
code
Compute prefix sums P[0..n]
Compress all numbers that will appear
Initialize Fenwick tree with size = M
Insert P[0] (which is 0) into the tree
total = 0
for j = 1 … n:
T = P[j] - k
idx = number of compressed values ≤ T (bisect_right)
cnt_le = fenwick.query(idx) # inserted prefix sums ≤ T
total += j - cnt_le # (1) gives those > T → sum < k
fenwick.update( index(P[j]), 1 ) # add current prefix for future queries
return total
4. Correctness Proof
We prove that the algorithm returns exactly the number of subarrays with sum
< k.
Lemma 1
For any j (1 ≤ j ≤ n) the algorithm adds to total the number of indices
i (0 ≤ i < j) such that P[j] - P[i] < k.
Proof.
At step j the Fenwick tree contains exactly the prefix sums P[0] … P[j‑1],
each inserted once. cnt_le is the count of those i with P[i] ≤ P[j] - k.
All remaining i (there are j - cnt_le of them) satisfy P[i] > P[j] - k.
By inequality (1) this is equivalent to P[j] - P[i] < k. ∎
Lemma 2
Every subarray nums[l … r] with sum < k is counted exactly once.
Proof.
The subarray corresponds to indices i = l and j = r+1.
When the loop reaches j = r+1, Lemma 1 tells us that the algorithm adds
1 for this specific i (because P[i] > P[j] - k holds).
For any other j' ≠ j the pair (i, j') either does not satisfy i < j' or
does not represent the same subarray. Hence the subarray contributes exactly
once. ∎
Lemma 3
If a subarray sum is ≥ k, it is never counted.
Proof.
For such a subarray we have P[j] - P[i] ≥ k → P[i] ≤ P[j] - k.
At step j this i belongs to the cnt_le group and is not included in
j - cnt_le. Hence it is not counted. ∎
Theorem
total returned by the algorithm equals the number of subarrays of nums
with sum strictly less than k.
Proof.
By Lemma 2 every qualifying subarray contributes exactly one to total.
By Lemma 3 no non‑qualifying subarray contributes.
Therefore total is precisely the desired count. ∎
5. Complexity Analysis
Prefix sums & collection: O(n) time, O(n) space. Coordinate compression: sorting O(n log n) time, O(n) space. Main loop: n iterations, each does two Fenwick operations and a binary
search → O(log n) per iteration.
Total time: O(n log n)
Extra space: O(n) (prefix array, sorted values, Fenwick tree).
6. Reference Implementation (Python)
python
import bisect
def count_subarrays_sum_less_than_k(nums, k):
"""
Returns the number of contiguous subarrays of `nums` whose sum is < k.
"""
n = len(nums)
# 1. prefix sums
prefix = [0] * (n + 1)
for i in range(1, n + 1):
prefix[i] = prefix[i - 1] + nums[i - 1]
# 2. collect values for coordinate compression
vals = set()
for p in prefix:
vals.add(p)
for j in range(1, n + 1):
vals.add(prefix[j] - k)
sorted_vals = sorted(vals)
m = len(sorted_vals)
# map original value -> 1‑based index for Fenwick
val_to_idx = {v: i + 1 for i, v in enumerate(sorted_vals)}
# 3. Fenwick tree implementation
class Fenwick:
def __init__(self, size):
self.n = size
self.tree = [0] * (size + 1)
def update(self, i, delta):
while i <= self.n:
self.tree[i] += delta
i += i & -i
def query(self, i):
"""sum of positions 1..i (i may be 0)"""
s = 0
while i > 0:
s += self.tree[i]
i -= i & -i
return s
bit = Fenwick(m)
# 4. initial insertion: P[0] = 0
bit.update(val_to_idx[0], 1)
total = 0
for j in range(1, n + 1):
T = prefix[j] - k
# number of compressed values <= T
idx = bisect.bisect_right(sorted_vals, T) # 0 … m
cnt_le = bit.query(idx) # count of inserted P[i] ≤ T
total += j - cnt_le # those > T give sum < k
# insert current prefix sum
bit.update(val_to_idx[prefix[j]], 1)
return total
The function follows exactly the algorithm proven correct above and runs in
O(n log n) time with O(n) additional memory.