Data Structures & AlgorithmsHardAmazon · Microsoft OA

Problem: Find a target's index in a rotated sorted array of distinct values in O(log n).

Problem: Find a target's index in a rotated sorted array of distinct values in O(log n).
def search(a, t):
    lo, hi = 0, len(a) - 1
    while lo <= hi:
        m = (lo + hi) // 2
        if a[m] == t: return m
        if a[lo] <= a[m]:
            if a[lo] <= t < a[m]: hi = m - 1
            else: lo = m + 1
        else:
            if a[m] < t <= a[hi]: lo = m + 1
            else: hi = m - 1
    return -1
print(search([15, 18, 22, 3, 7, 9, 11], 9), search([15, 18, 22, 3, 7, 9, 11], 16))
What is printed?
  1. A. 5 0
  2. B. 4 -1
  3. C. 6 -1
  4. D. 5 -1

Correct answer: D. 5 -1

At least one half around mid is sorted; check whether the target lies in that half's range. 9 is found at index 5. 16 would lie between 15 and 18 but is absent, so the search ends with −1.

More Coding Interview Problems questions

Exams that ask this topic