KatInterview

Find Index of Local Minimum Using Binary Search

Heaps, Sorting & SearchModel answer
MediumModel answerHeaps, Sorting & Searcharraysbinary-searchalgorithms

Last updated

Locate a local minimum in an array of integers in logarithmic time while handling flat regions and boundaries.

An element at index $i$ in an array nums of size $n$ is defined as a local minimum if it is less than or equal to its existing neighbors. Formally:

  • For $0 < i < n - 1$: $nums[i] \le nums[i-1]$ and $nums[i] \le nums[i+1]$.
  • For $i = 0$: $nums[0] \le nums[1]$ (if $n > 1$).
  • For $i = n - 1$: $nums[n-1] \le nums[n-2]$ (if $n > 1$).
  • If $n = 1$, index 0 is always a local minimum.

Write a function to return the index of a local minimum in nums in $O(\log n)$ time. When encountering equal elements or multiple paths, favor shifting left so that plateaus resolve to the leftmost reachable index.

Function Signature

def find_local_minimum(nums: list[int]) -> int:

Constraints

  • $1 \le n \le 10^5$
  • $-10^9 \le nums[i] \le 10^9$

Examples

Example 1:

Input: nums = [9, 6, 3, 4, 7]
Output: 2
Explanation: nums[2] = 3, which is <= 6 and <= 4.

Example 2:

Input: nums = [1, 2, 3, 4, 5]
Output: 0
Explanation: nums[0] = 1, which is <= nums[1].

Example 3:

Input: nums = [2, 2, 2]
Output: 0
Explanation: All values are identical. Index 0 is a local minimum.

Hints

Hint 1

Think about the direction of slope at index `mid`. If `nums[mid] <= nums[mid + 1]`, can you guarantee a local minimum exists in the range `[lo, mid]`?

Hint 2

Consider the boundary invariants: if the array enters a subarray going downward from the left and exits going upward to the right, a valley must exist inside.

Hint 3

Is it possible to guarantee finding the absolute globally leftmost local minimum in O(log n) time? Why or why not?