3

Given an array , each element is one more or one less than its preceding element .find an element in it.(better than O(n) approach)

I have a solution for this but I have no way to tell formally if it is the correct solution:

Let us assume we have to find n.

  • From the given index, find the distance to n; d = |a[0] - n|
  • The desired element will be atleast d elements apart and jump d elements
  • repeat above till d = 0
4
  • Please give an example of such an array. Is binary search not good enough for this purpose? Commented Nov 11, 2013 at 8:32
  • @hgoebl no, it's only for sorted arrays, while OP means something like [2,3,2,1,2,3,4] Commented Nov 11, 2013 at 8:37
  • Your algorithm seems logical. Do you want a proof of correctness for your algorithm? Commented Nov 11, 2013 at 8:42
  • @AbhishekBansal: Yea, it sounds correct, but thats an instinct. You know how that feels like :) I just wanted to be sure, that it is correct, indeed. Commented Nov 11, 2013 at 11:43

2 Answers 2

8

Yes, your approach will work.

If you can only increase / decrease by one at each following index, there's no way a value at an index closer than d could be a distance d from the current value. So there's no way you can skip over the target value. And, unless the value is found, the distance will always be greater than 0, thus you'll keep moving right. Thus, if the value exists, you'll find it.

No, you can't do better than O(n) in the worst case.

Consider an array 1,2,1,2,1,2,1,2,1,2,1,2 and you're looking for 0. Any of the 2's can be changed to a 0 without having to change any of the other values, thus we have to look at all the 2's and there are n/2 = O(n) 2's.

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

Comments

0

Prepocessing can help here. Find Minimum and Maximum element of array in O(n) time complexity. If element to be queried is between Minimum and Maximum of array, then that element is present in array, else that element is not present in that array.So any query will take O(1) time. If that array is queried multiple times, than amortized time complexity will be lesser that O(n).

1 Comment

Only if the multiple queries are often outside the range of the array.

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.