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
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Find the color of given node in an infinite binary tree
- Search insert position of K in a sorted array
- Find missing element in a sorted array of consecutive numbers
- Find element position in given monotonic sequence
- 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 the minimum element in a sorted and rotated array
- Find the element that appears once in a sorted array
- Check if array can be sorted by swapping pairs with GCD of set bits count equal to that of the smallest array element
- Check if array can be sorted by swapping pairs having GCD equal to the smallest element in the array
- Find the position of the given row in a 2-D array
- Given a sorted array and a number x, find the pair in array whose sum is closest to x
- Search an element in a sorted and rotated array
- Count of only repeated element in a sorted array of consecutive elements
- Last duplicate element in a sorted array
- First strictly greater element in a sorted array in Java
- First strictly smaller element in a sorted array in Java
- Maximum element in a sorted and rotated array
- Search an element in a reverse sorted array
- Kth smallest element in a row-wise and column-wise sorted 2D array | Set 1