Given a list of Numbers along with an index i and integer k , I wish the find the index of the number that is farthest (towards the left) from the number at index i and is less than k.
eg
if the array is
Index :0 1 2 3 4 5 6 7 .....
Array :3 4 1 5 5 4 3 7 .....
Assuming i = 7 and k = 4 , the answer would be 0
I have been trying to implement this using Red Black Trees, but I couldnt go any lower than O(n) . Is there any way I can reduce the complexity to O(logn) by using a different Data Structure ?
Actually, if the array is static and you want to make multiple queries for
O(log n)each, you don’t need that complicated data structures.What you’re actually asking for – “the number that is farthest (towards the left) from the number at index i and is less than k.” – can be transformed to “the leftmost number before
ithat is less thank“. Then you can see this as the following:j;j < i,jis the answer to the questioniare larger than or equal tok.To answer the first of these questions, all you need to know is: for position
i, what is the smallest number on positions0..i– let’s call thismin(i). Notice thatminis a monotonically decreasing function ofi– if themin(5) = 10, there is no way thatmin(6) = 15, sincemin(6)is the smallest number on positions0to6, and that necessarily includes the smallest number on positions0to5, which we know to be 10. (minis fairly trivial to construct – if we call the arraya, then:min(0) = a[0], andmin(i) = minimum(min(i - 1), a[i])fori > 0.)With this information, you can perform a binary search for the leftmost index
isuch thatmin(i) < k. Then, by the construction ofmin, we know that all numbers on positions from0toi - 1are greater than or equal tok. Soimust be the answer of the question.