Find an element in an array, but the element can jump

Viewed 869

There is an array where all but one of the cells are 0, and we want to find the index of that single non-zero cell. The problem is, every time that you check for a cell in this array, that non-zero element will do one of the following:

  1. move forward by 1
  2. move backward by 1
  3. stay where it is.

For example, if that element is currently at position 10, and I check what is in arr[5], then the element may be at position 9, 10 or 11 after I checked arr[5].

We only need to find the position where the element is currently at, not where it started at (which is impossible).

The hard part is, if we write a for loop, there really is no way to know if the element is currently in front of you, or behind you.

Some more context if it helps:

  1. The interviewer did give a hint which is maybe I should move my pointer back after checking x-number of cells. The problem is, when should I move back, and by how many slots?
  2. While "thinking out loud", I started saying a bunch of common approaches hoping that something would hit. When I said recursion, the interviewer did say "recursion is a good start". I don't know recursion really is the right approach, because I don't see how I can do recursion and #1 at the same time.
  3. The interviewer said this problem can't be solved in O(n^2). So we are looking at at least O(n^3), or maybe even exponential.
6 Answers
Related