Question presented to candidate: "Given an integer array where no two neighbours are equal, return the index of any peak โ an element bigger than both its neighbours, with the outside of the array counting as minus infinity. Please write it in Python and aim for better than linear time."
What a strong answer should cover:
- A peak always exists because out-of-range neighbours are minus infinity; any peak is accepted, not only the maximum.
- The O(n) scan first, then binary search on the slope: compare
nums[mid]withnums[mid + 1]and keep the half that must contain a peak. - The loop invariant that justifies it, and why the loop is
while lo < hiwithhi = mid. - O(log n) time and O(1) extra space; why the global maximum cannot be found this fast.
- Python specifics:
//for integer division (/returns a float that cannot index a list), no integer overflow in(lo + hi) // 2, and an explicit check for an empty list.
Clarifying questions expected:
- "Any peak or the highest one?"
- "Can neighbours be equal?"
- "What should an empty list return?"
Code / implementation expected: Yes โ a short iterative find_peak(nums) function in Python.