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?- A. 2
- B. 8
- C. 9
- 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
- Problem: In an n × n matrix whose rows and columns are both sorted, find the k-th smallest value by binary searching on the VALUE and…
- Problem: Reverse the nodes of a singly linked list from position m to n (1-based) in one pass. python class N: def init(s, v, nx=None)…
- Problem: Group a linked list's nodes at odd POSITIONS first, then the nodes at even positions, keeping relative order. python class N: def…
- Deep-copy a linked list whose nodes also have a random pointer. Which approach uses O(n) time and only O(1) extra space (besides the…
- Problem: Simulate an LRU cache of capacity 3 (get returns −1 on a miss; a get or put marks the key most recently used). python from…
- Problem: Insert keys into an empty BST in the given order, then report the lowest common ancestor of three pairs. python class T: def…