![]() |
VOOZH | about |
Given an array arr[0 .. n-1] of n distinct integers. The task is to find a local minimum in the array. An element arr[x] is considered a local minimum if it is smaller than both of its adjacent elements, meaning
arr[x] < arr[x - 1] and arr[x] < arr[x + 1] for indices where 1 <= x <= n - 2. For corner elements, arr[0] is a local minimum if arr[0] < arr[1], and arr[n - 1] is a local minimum if arr[n - 1] < arr[n - 2].
Note: Since multiple local minima may exist, the goal is to find any one local minimum efficiently.
Examples:
Input: arr[] = {9, 6, 3, 14, 5, 7, 4}
Output: 2
Explanation: The output prints the index of 3 because it is smaller than both of its neighbors 6 and 14. Note that the indexes of elements 5 and 4 are also valid outputs.Input: arr[] = {23, 8, 15, 2, 3}
Output: 1
Explanation: The output prints the index of 8 because it is smaller than both of its neighbors 23 and 15. Another valid local minimum is 2 at index 3.Input: arr[] = {5, 4, 3, 2, 1}
Output: 4
The idea is to use Binary search, to efficiently find the smallest index of a local minimum. The thought process begins with the observation that if the middle element is a local minimum, we store it and continue searching on the left for a smaller index. If the left neighbor is smaller, a local minimum must exist on the left, so we move left. Otherwise, we move right. This ensures an O(log n) solution by always reducing the search space by half, guaranteeing we find the smallest index where the local minimum condition holds.
Steps to implement the above idea:
2