A list of sorted and rotated element is given. Elements are either sorted in ascending or descending order. For example – I’ve list of sorted elements as follows
10,12,14,16,18,20,51,53,54,59
Now this list is rotated by X number of times and then it looks as follows.
51,53,54,59,10,12,14,16,18,20
If you want to insert an element in this list what would be the most efficient method to do it.
For element to be inserted is 13, If list is traversed in a linear fashion, false insertion may happen between 59 and 10.
I’m not expecting any code, rather discussion of algorithm is what I’m looking forward to.
Value 21 can be inserted as either first /last element. Account for boundary condition such as – to be inserted element, the first and last element are of same value.
This can be solved in log(N) time. In short:
More on point 1:
Say you need to find the biggest element in 51,53,54,59,10,12,14,16,18,20.
First you pick the middle element (say it would be 12). 12 is smaller than 51, therefore the biggest element is on the left from 12. You split the interval in half, and get 54. 54 is greater than 51, therefore the biggest element is between 54 and 12. And so on