VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-local-minima-array/

⇱ Find a local minima in an array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find a local minima in an array

Last Updated : 3 Mar, 2025

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

Approach- Using Binary Search - O(log n) Time and O(1) Space

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:

  • Initialize l to 0, r to length of arr - 1, and ans to -1 to store the smallest local minimum index.
  • Use a while loop to perform binary search until l is less than or equal to r.
  • Compute mid as l + (r - l) / 2 to avoid overflow.
  • Check if arr[mid] is a local minimum by comparing it with its neighbors:
  • If arr[mid] is smaller than both arr[mid - 1] and arr[mid + 1], update ans and continue searching left.
  • If arr[mid - 1] is smaller, move r to mid - 1 to explore the left half. Otherwise, move l to mid + 1 to explore the right half.
  • Finally, return ans.

Output
2


Comment
Article Tags: