Index Match


Collapse Content

Given a sorted Array ar of integers with no duplicates, find the spot where ar[i] == i.

It's super-easy to find a solution in O(n) time, but can you code an O(log n) solution?

Challenge

Print the index where they match, or -1 if there is none.

Please sign in or sign up to submit answers.

Alternatively, you can try out Learneroo before signing up.

Comments

  • I have implemented binary search by recursion.
    Here is my code:

    static void doStuff(int[] ar){
    //your code here
    int low = 0;
    int high = ar.length-1;

    cont...
  • 曾國峻 I needed to keep track of the index and pass it back up the recursion to solve it. Because each time the binary search needed to look at the > side of the array, the index forgets about the lower half of the array. Here is my solution in Ruby:

    cont...
  • Better to solve without recursion. maybe can be a bit more elegant, but works.

        int start = 0;
        int end = ar.length-1;
    
        int i = start + ((end - start) / 2);
    
    cont...
Contact Us
Sign in or email us at [email protected]