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?- A. 5 0
- B. 1 0
- C. 5 2
- 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
- Problem: Return the k-th smallest element of the union of two sorted arrays (k is 1-based) in O(log(m + n)). python def kth(a, b, k): if…
- Problem: Reverse a singly linked list of order IDs. python class Node: def init(self, v, nxt=None): self.v, self.next = v, nxt def…
- Problem: Return the middle node of a linked list (the second middle when the length is even). python class Node: def init(self, v…
- Problem: Remove the k-th node from the end of a list in one pass. python class Node: def init(self, v, nxt=None): self.v, self.next = v…
- Problem: Merge two sorted linked lists into one sorted list. python class Node: def init(self, v, nxt=None): self.v, self.next = v, nxt…
- Problem: Detect whether a linked list has a cycle and return the value where the cycle starts (None if acyclic). python class Node: def…