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 Missing Number
- Search an element in a sorted and rotated array
- Median of two sorted arrays of same size
- k largest(or smallest) elements in an array | added Min Heap method
- Find the smallest and second smallest elements in an array
- Maximum and minimum of an array using minimum number of comparisons
- Ceiling in a sorted array
- Search in a row wise and column wise sorted matrix
- Find the repeating and the missing | Added 3 new methods
- Count number of occurrences (or frequency) in a sorted array
- Find whether an array is subset of another array | Added Method 3
- Find a Fixed Point (Value equal to index) in a given array
- Find the maximum element in an array which is first increasing and then decreasing
- Find a pair with the given difference
- Find four elements that sum to a given value | Set 1 (n^3 solution)