1

Here is another interview question

Array contains elements where next element can be either x+1 or x-1 if previous element is x.

Prev element = x
Next element = x+1/ x-1

Example: {2, 3, 4, 3, 2, 1, 0, -1, 0, 1, 2, 3, 2, 1}

If I need to search for 0 what is best algorithm we can choose?

If I sort it then it will be O(nlogn) and I can just traverse array in O(n) so O(n) is still better

Creating binary search tree will be again O(n) and search in BST is O(log) so still its O(n).

Its a random array and next element is +1 or -1 doesnot leads to any search pattern. If you guys can think of any search pattern that can be utilised here to perform better search then let me know.

8
  • I feel it can be done in O(n) Commented Mar 8, 2014 at 12:47
  • there's no such thing as "best" - you need a utility function. Commented Mar 8, 2014 at 12:47
  • 1
    Well of course it can be done in O(n). Just use whatever indexOf is in your chosen language. Commented Mar 8, 2014 at 12:48
  • Question is not very clear. Index 1 is 3. Previous is 2. So next can be either 2+1(3) or 2-1(1). Why is it 4? Commented Mar 8, 2014 at 12:49
  • 2
    Your own proposals ignore useful information. Consider: the first element is 2, where can the value 0 not be found ? Now get on with it. You will find that the asymptotic complexity is O(n). Commented Mar 8, 2014 at 12:50

1 Answer 1

3

The obvious thing to do is:

  1. Consider the first value, let's say the value is n. Is it 0?
  2. If yes, you are done.
  3. If not, step forward abs(n) elements, and go to step 1.

You can step over multiple elements because the absolute difference between two adjacent values is always 1.

So, given the array in your question, you do the following:

  • Item 0 is 2. That's not zero, and so you step to item 2.
  • Item 2 is 4. That's not zero, step forward 4 items to item 6.
  • Item 6 is 0. You are done.
Sign up to request clarification or add additional context in comments.

4 Comments

Not sure about "done", there could be multiple 0s. I know, the question is unclear on this (which raises the question, why do beginners usually ignore corner cases?)
@Karoly This will find the first 0. It's easy to extend to find them all.
Well, it took me a little while to understand the rules, but once I did it was obvious. This is an old trick. One that I use to great effect in my program to optimise checking for closest distance between two lines where the lines are modelling as connected series of line segments.
Programming Pearls is a nice book for algos.

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.