Searching An Infinite Array

December 9, 2016

Given an array of positive integers in ascending order, of infinite size, find the index of an integer k in the array, or determine that it does not exist. Your solution must work in time logarithmic in the index of the requested integer.

Your task is to write a program that finds the requested integer. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.


Pages: 1 2

2 Responses to “Searching An Infinite Array”

  1. Paul said

    A solution in Python

    def search(iterable, x):
        section = [next(iterable)]
        n = 1
        while section[-1] < x:
            n *= 2
            section = list(islice(iterable, n))
        ind = bisect.bisect_left(section, x)
        return ind + n - 1 if section[ind] == x else None
  2. xvanger said

    just do binary search for the first n elements which will be in logarthimic time

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: