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 the index of first 1 in an infinite sorted array of 0s and 1s
- Find the element that appears once in a sorted array
- Find first and last positions of an element in a sorted array
- Find the minimum element in a sorted and rotated array
- Find the only repeating element in a sorted array of size n
- Find element in a sorted array whose frequency is greater than or equal to n/2.
- Find index of an extra element present in one sorted array
- Check if given array is almost sorted (elements are at-most one position away)
- Find position of the given number among the numbers made of 4 and 7
- Last duplicate element in a sorted array
- k-th missing element in sorted array
- Check for Majority Element in a sorted array
- Search an element in a sorted and rotated array
- First strictly smaller element in a sorted array in Java
- First strictly greater element in a sorted array in Java