Data Structures & AlgorithmsHardAmazon · Microsoft OA

Problem: Return the index of ANY peak element (strictly greater than its neighbours; a[−1] = a[n] = −∞) in O(log n).

Problem: Return the index of ANY peak element (strictly greater than its neighbours; a[−1] = a[n] = −∞) in O(log n).
def peak(a):
    lo, hi = 0, len(a) - 1
    while lo < hi:
        mid = (lo + hi) // 2
        if a[mid] < a[mid + 1]: lo = mid + 1
        else: hi = mid
    return lo
print(peak([1, 3, 20, 4, 1, 0, 7, 8, 9, 2]))
What is printed?
  1. A. 2
  2. B. 8
  3. C. 9
  4. D. 3

Correct answer: A. 2

mid = 4: a[4] = 1 > a[5] = 0, so hi = 4; mid = 2: 20 > 4, hi = 2; mid = 1: 3 < 20, lo = 2. It returns index 2 (value 20). The search climbs toward some peak, not the global maximum 9 at index 8.

More Coding Interview Problems questions

Exams that ask this topic