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

Problem: Find a peak element (strictly greater than its neighbours; outside the array counts as −∞). Return its index.

Problem: Find a peak element (strictly greater than its neighbours; outside the array counts as −∞). Return its index.
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, 2, 1, 3, 5, 6, 4]), peak([5, 4, 3]))
What is printed?
  1. A. 5 0
  2. B. 1 0
  3. C. 5 2
  4. D. 1 2

Correct answer: A. 5 0

If a[mid] < a[mid + 1], the slope rises to the right and a peak must exist there (the right edge counts as −∞); otherwise a peak is at mid or to its left. For the first array the search lands on 6 at index 5 (index 1 is also a peak, but this search goes right). For a strictly decreasing array index 0 is the peak. O(log n) – the array need not be sorted.

More Coding Interview Problems questions

Exams that ask this topic