I would like to find the lowest value in some range.
Do I have to iterate array each time or is there any dynamic method?
Lets say I have input array:
index: 0 1 2 3 4 5 6 7
value: 1 4 6 1 6 7 2 3
and then I have to choose smallest in range < a,b > (inclusive). For example:
min(0,7) = 1
min(0,2) = 1
min(4,6) = 2
min(1,2) = 4
Im interested in the fastest solution, it would be the best to get the results in constant time.
Array won't be changed in meantime.
If you are going to perform multiple queries over the same set of numbers then you will want to construct a Cartesian Tree.
As the article says, the queries can be performed in constant time.
You can use segment tree for this question. This is one of the best tutorial on segment tree and range minimum query.
I am giving JAVA implementation and the code is self explanatory, please let me know if you have any doubts.
This is a standard task. You can use std library functionality. It should be the fastest possible. The example from here:
P.S. You can not get result in constant time, since if you need minimum between N elements you need to check each element. Minimum task complexity is O(N).
You can try the following (not sure if I am missing something)
If you are allowed some preprocessing, then you can have an array of local minima( valleys ).
This array shall be sorted as per the respective indices.
Once you get an interval, perform a binary search of the lower index in the minima array. Choose the greater one in that array. say I1
Then perform a binary search of the higher given index in the minima array. Choose the smaller one in that array. say I2
If I2 >= I1, then atleast one local minimum exists in the interval. Just compare values at the minima in that interval and at the boundaries to get the answer.
Else, no local minimum exists in the interval. In this case, the minimum shall be at the boundary of the interval. Just compare the two values and get the lower one.