Array Search Unknown Size LeetCode (Search element in an array of unknown size)

Suppose you have a sorted array of infinite numbers, how would you search an element in the array?

HINTS:
  1. 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.
  2. 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.
  3. Let low be pointing to 1st element and high pointing to 2nd element of array, Now compare key with high index element,
    1. if it is greater than high index element then copy high index in low index and double the high index.
    2. if it is smaller, then apply binary search on high and low indices found.

This question is very popular in Amazon SDE Interviews and is also popular in LeetCode A collection of hundreds of interview questions and solutions are available in our blog at Interview Question Solutions

 

Solution:

 

No comments:

Post a Comment