Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA

Problem: Search a target in a sorted array of distinct values that has been rotated at an unknown pivot.

Problem: Search a target in a sorted array of distinct values that has been rotated at an unknown pivot.
def search(a, t):
    lo, hi = 0, len(a) - 1
    while lo <= hi:
        mid = (lo + hi) // 2
        if a[mid] == t: return mid
        if a[lo] <= a[mid]:
            if a[lo] <= t < a[mid]: hi = mid - 1
            else: lo = mid + 1
        else:
            if a[mid] < t <= a[hi]: lo = mid + 1
            else: hi = mid - 1
    return -1
a = [15, 18, 22, 3, 6, 9, 12]
print(search(a, 6), search(a, 18), search(a, 10))
What is printed?
  1. A. 4 1 5
  2. B. 3 1 -1
  3. C. 4 1 -1
  4. D. -1 1 -1

Correct answer: C. 4 1 -1

One half around mid is always sorted; check whether the target lies in that sorted half, else go to the other half. 6 is at index 4, 18 at index 1, 10 is absent. O(log n). Using a[lo] < a[mid] (strict) breaks when lo == mid.

More Coding Interview Problems questions

Exams that ask this topic