Suppose you have a sorted array of infinite numbers, how would you search an element in the array?
Source: Amazon Interview Experience.
Since array is sorted, the first thing clicks into mind is binary search, but the problem here is that we don’t know size of array.
If the array is infinite, that means we don’t have proper bounds to apply binary search. So in order to find position of key, first we find bounds and then apply binary search algorithm.
Let low be pointing to 1st element and high pointing to 2nd element of array, Now compare key with high index element,
->if it is greater than high index element then copy high index in low index and double the high index.
->if it is smaller, then apply binary search on high and low indices found.
Below are implementations of above algorithm
Element found at index 4
Let p be the position of element to be searched. Number of steps for finding high index ‘h’ is O(Log p). The value of ‘h’ must be less than 2*p. The number of elements between h/2 and h must be O(p). Therefore, time complexity of Binary Search step is also O(Log p) and overall time complexity is 2*O(Log p) which is O(Log p).
This article is contributed by Gaurav Sharma. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
- Find missing element in a sorted array of consecutive numbers
- Find the element that appears once in a sorted array
- Find the minimum element in a sorted and rotated array
- Find index of an extra element present in one sorted array
- Find element in a sorted array whose frequency is greater than or equal to n/2.
- Find element position in given monotonic sequence
- Last duplicate element in a sorted array
- k-th missing element in sorted array
- Maximum element in a sorted and rotated array
- Search an element in a sorted and rotated array
- Find the position of the given row in a 2-D array
- First strictly smaller element in a sorted array in Java
- First strictly greater element in a sorted array in Java
- Count of only repeated element in a sorted array of consecutive elements
- Given a sorted array and a number x, find the pair in array whose sum is closest to x