You are given a sequence of n numbers A(1), … , A(n), with a very special proper
ID: 3589228 • Letter: Y
Question
You are given a sequence of n numbers A(1), … , A(n), with a very special property, that adjacent numbers are “off” by no more than 1. For example, here is a valid sequence: [100, 99, 99, 98, 99, 100, 100, 101, 102, 103, 104, 105, 104, 103, 103, 103, 102]. Say the first number in the sequence is x, the last one is y, and you are given a number z, such that x < z < y . You have to find the location of z in the sequence (or report that it does not exist). If the element z appears more than once, you are free to report 48 | ANALYSIS AND DESIGN OF ALGORITHMS any location you choose. The time complexity of your algorithm should be O(log n) or better.
Explanation / Answer
Answer: -
First observation to make is that z MUST EXIST in the sequence, as a[1] < z < a[n], and there are no “jumps” in the sequence.
Second observation is that binary search works in the following sense: if we compare z to a[n/2], and if z > a[n/2], then z must exist in a[n/2..n].
Similarly, if z < a[n/2], then z must exist in a[1..n/2]. This leads to a straight forward log(n) algorithm.
Note that we do not claim that z does not exist in the other half – we focus our effort on the half where z is GUARANTEED to exist.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.