I have a small algorithm problem. I have an array for example.
array[10] = {23,54,10,63,52,36,41,7,20,22};
now given an input number for example 189 i want to know that in which slot it should lie.
for example this input should lie in 4 index in the array because
23+54+10+63 = 150 and if we add 52 then sum will be 202 which will cover the range where 189 should lie. so the answer should be 4.
I want to find an amortized constant time algorithm may be in the first step we do some prepossessing on the array so that all the next queries we can get in constant time.
The input number will always be in between 1 and sum of all the entries in array
Thanks
The natural solution would be to first build an array with the cumulative sums. This would look like
and then use a binary search such as the lower_bound algorithm to find where to insert. That would be
O(log(n)). Assuming that your number of slots is constant, this solution is also time-constant. But I guess you want the lookup to beO(1)in terms of the number of slots. In this case, you will have to make a full lookup table. Since the size of these numbers is relatively small, that is perfectly doable:Using this, the slot number is simply
lookup[number].