52

I was asked the following question in my interview yesterday:

Consider a Java or C++ array say X which is sorted and no two elements in it are same. How best can you find an index say i such that element at that index is also i. That is X[i] = i.

As clarification she also gave me an example:

Array X : -3 -1 0 3 5 7
index   :  0  1 2 3 4 5

Answer is 3 as X[3] = 3.

The best I could think was a linear search. After the interview I though a lot on this problem but could not find any better solution. My argument is: the element with the required property can be anywhere in the array. So it could also be at the very end of the array so we need to check every element.

I just wanted to confirm from the community here that I'm right. Please tell me I'm right :)

10
  • 5
    Some algorithm similar to binary search should give better solution Commented Nov 13, 2010 at 12:56
  • 1
    I don't think Amazon would like you exposing their interview questions... Commented Nov 13, 2010 at 13:02
  • 2
    4 favorits?! 5 upvotes?! Where are you (upvoters, favorite clickers) from? It's very simple question. I would not have taken a job seeker who does not know anything about a binary and interpolation search. Commented Nov 13, 2010 at 13:11
  • 1
    Peter: I've edited to remove the company name. Alexey: I knew binary search but could not think of how to apply it. Commented Nov 13, 2010 at 13:36
  • 10
    @Alexey: if they just wanted to know whether the candidate knows about binary search, then they'd just ask to find i where x[i] = 3 in a sorted array. This question is an interesting one. If the candidate answers it immediately, chances are they've seen it before, but they might be clever and spotted the extra trick immediately. If the candidate answers it after 30 seconds, they've spotted the trick. If they can't answer, they haven't spotted it. To separate the clever from the knowledgeable, ask it with an array of float, see if you get the same (now incorrect) answer ;-) Commented Nov 13, 2010 at 14:05

10 Answers 10

105

This can be done in O(logN) time and O(1) space by using a slightly modified binary search.

Consider a new array Y such that Y[i] = X[i] - i

Array X : -3 -1   0  3  5  7
index   :  0  1   2  3  4  5
Array Y : -3 -2  -2  0  1  2

Since the elements in X are in increasing order, the elements in the new array Y will be in non-decreasing order. So a binary search for 0 in Y will give the answer.

But creating Y will take O(N) space and O(N) time. So instead of creating the new array you just modify the binary search such that a reference to Y[i] is replaced by X[i] - i.

Algorithm:

function (array X) 
       low  = 0
       high = (num of elements in X) - 1

       while(low <= high) 
               mid = (low + high) / 2

               // change X[mid] to X[mid] - mid
               if(X[mid] - mid == 0)
                       return mid

               // change here too
               else if(X[mid] - mid < 0)
                       low = mid + 1;

               else
                       high = mid - 1;
       end while

       return -1 // no such index exists...return an invalid index.

end function

Java implementation

C++ implementation

Sign up to request clarification or add additional context in comments.

10 Comments

Thank you for the explanation. I knew binary search but never though I'd to apply it in this manner.
@codaddict: Is "non-decreasing order" ascending order?
I don't understand why the resulting array Y is non-decreasing. Lets say X is [3,3,3,3] then Y would be [3, 2, 1, 0]. It is clearly decreasing. I think I'm missing something here. can someone Please enlighten me?
@Srikanth: The question has a requirement "no two array elements are same".
Everything is fine except one thing: you didn't really prove that array Y is non-decreasing (which is true for the conditions given) and thus you didn't highlight the condition that makes it non-decreasing. What changes if you use floating point numbers instead of integers? In your explanation nothing changes but the algorithm is wrong for the floats and true algorithm is o(n).
|
9

There are some faster solutions, averaging O(log n) or in some cases O(log log n) instead of O(n). Have a google for "binary search" and "interpolation search", you're likely to find very good explanations.

If the array is unsorted, then yes, the element is anywhere and you can't get under O(n), but that's not the case with sorted arrays.

--

Some explanation on interpolation search as requested:

While the binary search only concerns with comparing two elements in terms of "greater / not greater", the interpolation search tries to also make use of numerical values. The point is: You have a sorted range of values from 0 to, say, 20000. You look for 300 - binary search would start at the half of range, at 10000. The interpolation search guesses that 300 would probably be somewhere closer to 0 than 20000, so it would check the element 6000 first instead of 10000. Then again - if it's too high, recurse into lower subrange, and it's too low - recurse into upper subrange.

For a big array with +- uniform distribution of values, interpolation search should behave much faster than binary search - code it and see for yourself. Also, works best if first you use one interpolation search step, then one binary search step, and so on.

Note that it's the thing a human does intuitively when looking up something in a dictionary.

7 Comments

+1 for interpolation search reference. It is described in D. Knuth books also.
Can you please explain how to apply interpolation search for this problem?
-1, you haven't explained how to apply interpolation search to this problem. The non-obvious step is that for integers, if x[i] is strictly increasing, then x[i]-i is non-decreasing.
@Kos: the question is not, "how do I find an index i so that x[i] == 300". The question is, "how do I find an index i so that x[i] == i". Without accounting for that, I don't see how this answer can be considered correct (although it's certainly a good description of an interpolation search).
... Steve you're right :), for some reason till now I failed to notice what's this problem is about; aparrently I need to give up on my programming skills and focus on reading skills instead. John, for interpolation search just refer to Codaddict's post and replace the line int mid = ... for appropriate one for interpolation search. Sorry for the confusion, everyone :).
|
9

Its not require to think in terms of any array Y as suggested in answer by @codaddict.

Use binary search and check the middle element of given array, if it is lower than its index, than we do not need to check for any lower index because the array is sorted and so if we move to the left, subtracting m indexes and (at least) m value, all subsequent elements will also be too small. E.g. if arr[5] = 4 then arr[4] <= (4 - 1) and arr[3] <= (4 - 2) and so on. Similar logic can be apply if middle element is greater than its index.

Here is simple Java implementation:

int function(int[] arr) {
        int low = 0;
        int high = arr.length - 1;

        while(low <= high) {
            int mid = high - (high - low) / 2;

            if(arr[mid] == mid) {
                 return mid;
            } else if(arr[mid] < mid) {
                 low = mid + 1;
            } else {
                 high = mid - 1;
            }
        }

        return -1; // There is no such index
}

Note that the above solution would work only if all elements are distinct.

2 Comments

What if arr[5] = 3, then solution can be in arr[4] still or be in arr[6]. I don't think we can pick a direction in this case with the above code
@user814628, in this case arr[4] must be less than 3 as arr is sorted, and so we must look from index 6 onwards for solution.
7

I think this would be faster.

Start in the middle of the list

If X[i] > i then go to the middle of the remaining left side

if X[i] < i then go the middle of the remaining right

Keep doing that and it will reduce the number of possible elements by half for each loop

Comments

3

You can perform a binary search: search the middle, if the value is lower than the index, than no lower index will contain the same value.

Then you search the higher half, and continue till you find the element, or reach one element span.

7 Comments

"You can perform a binary search" - What is your key?
the value of the cell is the "value" and the index is the "key".
(under the assumption the length of the array is knows)
-1, the value of the cell is not the value to use in the binary search.
+1: I don't think you explained it quite as clearly as some others (e.g. JOTN), but seems you were first with the answer.
|
1

This is a solution I came up with, and it works if there are duplicates (I mistakenly overlooked that caveat of there being no duplicates).

//invariant: startIndex <= i <= endIndex

int modifiedBsearch(int startIndex, int endIndex)
{
   int sameValueIndex = -1;
   int middleIndex = (startIndex + endIndex) /2;
   int middleValue = array[middleIndex];
   int endValue = array[endIndex];
   int startValue = array[startIndex];

   if(middleIndex == middleValue)
      return middleValue;
   else {
      if(middleValue <= endIndex)
         sameValueIndex = modifiedBsearch(middleIndex + 1, endIndex)

      if(sameValueIndex == -1 && startValue <= middleIndex)
         sameValueIndex = modifiedBsearch(startIndex, middleIndex -1);
   }

   return sameValueIndex;

}

I would guess this takes O(log n) time, but this isn't clear in first glance???

If you're unlucky, it'll take O(n log n) time (the height of the stack tree will be log n, and it will be a full tree, with n nodes in the last level, n/2 in next to last, etc.).

So, on average it will be between O(log n) and O(n log n).

1 Comment

it can't be O(n log n), you access each element at most once.
0

of the top of my head, doing binary splitting might be faster.

look at the middle value, if it is high then what you need, re-search in the lower half.

After one comparison, you have already spilt your data set in half

Comments

0

After reading the question it seems like there is one scenario that can be used to speed up the lookup. When comparing the position to the value, if the value is greater then the position then the value can be used as the next position to evaluate. This will help jump through the array faster. This can be done because the array is sorted. The values that we are skipping are conceptually shifted to the left in the array and are in the wrong location.

Example:

int ABC[] = { -2, -5, 4, 7, 11, 22, 55 };

If my current position is 2 and it has a value of 4 they are not equal and conceptually the value 4 is shifted to the left. I can use the value of 4 as my next position because if the value 4 is out of position then everything less then 4 is out of position as well.

Some example code just for the sake of discussion:

void main()
{
    int X[] = { -3, -1, 0, 3, 5, 7};
    int length = sizeof(X)/sizeof(X[0]);

    for (int i = 0; i < length;) {
        if (X[i] > i && X[i] < length)
            i = X[i];                 // Jump forward!
        else if (X[i] == i) {
            printf("found it %i", i);
            break;
        } else
            ++i;
    }
}

Comments

0

Modified version of Binary Search would suffice I guess

Suppose the sequence is

Array : -1 1 4 5 6
Index :  0 1 2 3 4

Result : 1

or

Array : -2 0 1 2 4 6 10
Index :  0 1 2 3 4 5 6 

Result: 4

From both the examples we see that the required result will never lie on the right side if mid < a[mid]... pseudocode would look something like this

mid <- (first + last )/2

if a[mid] == mid then
       return mid

else if a[mid] < mid then
        recursive call (a,mid+1,last)

else 
         recursive call (a,first,mid-1)

Comments

0

Java:

public static boolean check (int [] array, int i)
{
    if (i < 0 || i >= array.length)
        return false;

    return (array[i] == i);
}

C++:

bool check (int array[], int array_size, int i)
{
    if (i < 0 || i >= array_size)
        return false;

    return (array[i] == i);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.