Given an array of Integers, and a range (low, high), find all contiguous subsequence in the array which have sum in the range.
Is there a solution b
O(NlogN)
with simple data structures is sufficient.
For contiguous subsequences, I think it means for subarrays.
We maintain a prefix sum list, prefix[i] = sum for the first i elements
. How to check if there exists a range rum between [low, high]
? We can use binary search. So,
prefix[0] = array[0]
for i in range(1, N)
prefix[i] = array[i] + prefix[i-1];
idx1 = binarySearch(prefix, prefix[i] - low);
if (idx1 < 0) idx1 = -1 - idx1;
idx2 = binarySearch(prefix, prefix[i] - high);
if (idx2 < 0) idx2 = -1 - idx2;
// for any k between [idx1, idx2], range [k, i] is within range [low, high]
insert(prefix, prefix[i])
The only thing we need to care is we also need to insert new values, thus any array or linked list is NOT okay. We can use a TreeSet, or implement your own AVL trees, both binary search and insertion would be in O(logN).