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
If all integers are non-negative, then it can be done in O(max(size-of-input,size-of-output))
time. This is optimal.
Here's the algorithm in C.
void interview_question (int* a, int N, int lo, int hi)
{
int sum_bottom_low = 0, sum_bottom_high = 0,
bottom_low = 0, bottom_high = 0,
top = 0;
int i;
if (lo == 0) printf ("[0 0) ");
while (top < N)
{
sum_bottom_low += a[top];
sum_bottom_high += a[top];
top++;
while (sum_bottom_high >= lo && bottom_high <= top)
{
sum_bottom_high -= a[bottom_high++];
}
while (sum_bottom_low > hi && bottom_low <= bottom_high)
{
sum_bottom_low -= a[bottom_low++];
}
// print output
for (i = bottom_low; i < bottom_high; ++i)
printf ("[%d %d) ", i, top);
}
printf("\n");
}
Except for the last loop marked "print output", each operation is executed O(N) times; the last loop is executed once for each interval printed. If we only need to count the intervals and not print them, the entire algorithm becomes O(N)
.
If negative numbers are allowed, then O(N^2)
is hard to beat (might be impossible).