Here is another interview question
Array contains elements where next element can be either x+1 or x-1 if previous element is x.
Prev element = x
Next element = x+1/ x-1
Example: {2, 3, 4, 3, 2, 1, 0, -1, 0, 1, 2, 3, 2, 1}
If I need to search for 0 what is best algorithm we can choose?
If I sort it then it will be O(nlogn) and I can just traverse array in O(n) so O(n) is still better
Creating binary search tree will be again O(n) and search in BST is O(log) so still its O(n).
Its a random array and next element is +1 or -1 doesnot leads to any search pattern. If you guys can think of any search pattern that can be utilised here to perform better search then let me know.
indexOfis in your chosen language.2, where can the value0not be found ? Now get on with it. You will find that the asymptotic complexity isO(n).