← Questions
Find a local minimum or peak with binary search
0
I was asked this
No reports yet. Sign in to say where you were asked it.
Given a non-empty integer array, return the index of a local minimum: an element no larger than its neighbours, where positions outside the array count as infinitely large. Use a left-biased binary search so the answer is deterministic, write it iteratively, and explain why the half you discard is safe. The same idea finds a peak.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
local_min(nums: list[int]) -> int— run the search onlo = 0, hi = n - 1; whilelo < hi, comparenums[mid]withnums[mid + 1]and keep the left half whennums[mid] <= nums[mid + 1], otherwise the right half. Returnlo.
Example
local_min([5, 3, 3, 4, 1, 2]) -> 1 # 3 <= 5 and 3 <= 3
local_min([9, 7, 7, 7, 8]) -> 1
local_min([1, 2, 3]) -> 0
local_min([3, 2, 1]) -> 2
local_min([4]) -> 0
Constraints
-
1 <= len(nums) <= 10^5; values fit in 32-bit integers; duplicates allowed. -
O(log n)time,O(1)space.
Clarifying questions
- Strict or non-strict comparison with neighbours? (With duplicates, only the non-strict version always has an answer.)
- Is any local minimum fine, or a specific one?
- How do the ends compare?
What a strong answer covers
- The invariant: the left neighbour of
lois larger thannums[lo](orlo = 0), andnums[hi]is no larger than its right neighbour (orhi = n - 1). Both survive each step, so whenlo == hithat index is a local minimum. - Why equality goes left:
nums[mid] <= nums[mid + 1]keepsmidas a valid right end of the range. - The peak version by flipping the comparison, and why both searches need no special handling at the ends.
- Tests: one element, two elements, plateaus of equal values, strictly monotone arrays.
Follow-ups
- Find a peak element instead.
- With duplicates and the strict definition, show an array where no local minimum exists and argue that no
O(log n)method can work in general. - A 2D version: find a cell no larger than its four neighbours.
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
