Find Peak Element

Updated on 26 May, 2025
Find Peak Element header image

Problem Statement

In this task, we are given a non-empty array where each element has a unique value which implies there are no consecutive repetitive elements. The goal is to identify a peak element, which is defined as an element that is greater than both its neighbors. A peak can exist anywhere within the interior of the array or at its edges considering the boundary values outside the array can be thought of as negative infinity (-∞). This means an element at the beginning or the end can be a peak if it is greater than its single neighbor within the array boundaries.

For efficiency, the solution needs to implement an algorithm with a time complexity of O(log n). This stipulation points towards the potential use of binary search or a similar divide-and-conquer strategy, given that a linear scan would take O(n) time.

Examples

Example 1

Input:

nums = [1,2,3,1]

Output:

2

Explanation:

3 is a peak element and your function should return the index number 2.

Example 2

Input:

nums = [1,2,1,3,5,6,4]

Output:

5

Explanation:

Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6.

Constraints

  • 1 <= nums.length <= 1000
  • -231 <= nums[i] <= 231 - 1
  • nums[i] != nums[i + 1] for all valid i.

Approach and Intuition

Given the constraints and requirements of the problem, a binary search approach is fitting. Here's a straightforward way to achieve our goal using binary search:

  1. Initialize two pointers, left and right, to the start and end of the array, respectively.
  2. Continuously narrow down the search space:
    • Compute the middle point mid using left and right.
    • If mid is a boundary of the array or if nums[mid] is greater than both nums[mid - 1] and nums[mid + 1], then mid is the peak and we can return it.
    • Otherwise, determine which side to continue the search on by comparing nums[mid] with its neighbors:
      • If nums[mid] is less than nums[mid + 1], the peak must be to the right; adjust left to mid + 1.
      • If nums[mid] is less than nums[mid - 1], the peak must be to the left; adjust right to mid - 1.
  3. Continue the above steps until the peak is located. The binary search ensures only half of the remaining array is searched in each iteration, leading to the required O(log n) complexity.

This method leverages the properties of binary search efficiently by reducing the problem space exponentially. Note that the assumption of no consecutive equal nums[i] is crucial since it guarantees that every movement in the search definitively moves towards a peak, avoiding any ambiguous cases.

Solutions

  • C++
  • Java
  • C
  • JavaScript
  • Python
cpp
class Solution {
public:
    int peakIndexInArray(vector<int>& arr) {
        int start = 0, end = arr.size() - 1;
        while (start < end) {
            int middle = (start + end) / 2;
            if (arr[middle] > arr[middle + 1])
                end = middle;
            else
                start = middle + 1;
        }
        return start;
    }
};

The provided C++ code is designed to find a peak element's index in a given array. This is achieved with a binary search strategy to efficiently locate a local peak, where an element is greater than its neighbors.

  • Understanding the Algorithm:

    • Initialize start to the beginning of the array and end to the last index.
    • Use a while loop to continue searching while start is less than end.
    • Compute the middle index using (start + end) / 2.
    • If the element at the middle index is greater than the subsequent element (arr[middle] > arr[middle + 1]), set end to middle. This action narrows the potential peak to the left section.
    • If not, update start to middle + 1 to focus on the right section.
    • Eventually, start will equal end, pointing to the peak element.
  • Return Value:

    • The function returns the index of the peak element once identified.

The optimal complexity of this method is O(log n), due to the binary search approach, making it highly efficient for large arrays. This solution assumes the array has a peak, which by problem definition, always exists.

java
public class Solution {
    public int locatePeak(int[] elements) {
        int left = 0, right = elements.length - 1;
        while (left < right) {
            int middle = (left + right) / 2;
            if (elements[middle] > elements[middle + 1]) right = middle;
            else left = middle + 1;
        }
        return left;
    }
}

This solution provides a method to locate a peak element in an array of integers, defined as an element that is greater than its neighbors. Implement this functionality using a Java method named locatePeak.

  • Input to the method is a single array of integers named elements.
  • The solution employs a binary search approach to efficiently find the peak.
  • Initialize two pointers: left starts at 0 and right at the last index of the array.
  • Continue the search as long as left is less than right:
    • Calculate the middle index.
    • Compare the middle element with its next element:
      • If the middle element is greater, narrow the search to the left of middle by setting right to middle.
      • Otherwise, focus on the elements right of middle by setting left to middle + 1.
  • The peak element's location is determined once left equals right, indicated by the left pointer.

This method is efficient, running in O(log n) due to its binary search nature, and it does not require any modifications to the original array. The return value directly provides the index of a peak element.

c
int peakIndex(int* elements, int size) {
    int left = 0, right = size - 1;
    while (left < right) {
        int midpoint = (left + right) / 2;
        if (elements[midpoint] > elements[midpoint + 1])
            right = midpoint;
        else
            left = midpoint + 1;
    }
    return left;
}

The given C program defines a function named peakIndex that finds the peak element in an array. A peak element is defined as an element that is greater than its neighbors or is at the boundary of the array. The function accepts two parameters: a pointer to an array of integers (elements) and the size of that array (size).

Here's how the function operates:

  1. Initialize two variables, left and right, to represent the boundaries of the current section of the array being considered. left starts at 0 and right starts at size - 1.
  2. Use a while loop to continue searching as long as left is less than right.
  3. Calculate the midpoint of the current section by averaging left and right.
  4. Compare the element at the midpoint with the element immediately following it.
    • If the midpoint element is greater than the next element, adjust the right boundary to midpoint to focus on the left subarray.
    • Otherwise, adjust the left boundary to midpoint + 1 to focus on the right subarray.
  5. Once the while loop completes, left will be pointing to the index of the peak element.

The function returns the index of the peak element in the array. The binary search approach ensures that the solution is efficient, with a time complexity of O(log n), where n is the size of the input array. This method leverages the properties of binary search by halving the search space with each iteration, making it significantly faster than a linear search approach.

js
var locatePeak = function (arr) {
    let left = 0,
        right = arr.length - 1;
    while (left < right) {
        let midpoint = Math.floor((left + right) / 2);
        if (arr[midpoint] > arr[midpoint + 1]) right = midpoint;
        else left = midpoint + 1;
    }
    return left;
};

The provided JavaScript function locatePeak efficiently identifies a peak element within an array using a binary search approach. The peak element is defined as an element that is greater than its adjacent elements. Here's a breakdown of how the function accomplishes this:

  • Define two pointers, left and right, that represent the bounds of the current search area within the array.
  • Use a while loop to continue the search as long as left is less than right.
  • Calculate the midpoint of the current range.
  • If the element at the midpoint is greater than the next element (arr[midpoint + 1]), adjust the right pointer to midpoint, narrowing the search to the left side.
  • If not, move the left pointer to midpoint + 1 to focus on the right side of the array.
  • The search terminates when left equals right, at which point left (or right, since they are equal) will be the index of a peak element.

This method leverages the binary search mechanism to efficiently locate a peak in logarithmic time complexity, making it suitable for large arrays. This function returns the index of the found peak which can then be used for further processing or verification.

python
class Solution:
    def peakElementSearch(self, array: List[int]) -> int:
        left = 0
        right = len(array) - 1
        while left < right:
            center = (left + right) // 2
            if array[center] > array[center + 1]:
                right = center
            else:
                left = center + 1
        return left

This summary details the implementation of the peakElementSearch function in Python, designed to find a peak element in an array. A peak element is defined as an element that is greater than its neighbors.

The function takes a list of integers as input and returns the index of a peak element. It utilizes a binary search approach to optimize the process, making it more efficient than a linear search.

  • Initialize left to zero and right to the length of the array minus one.
  • Enter a loop that continues until left is equal to right. This ensures that the search space is reduced efficiently.
  • Calculate the center index as the average of left and right indexes.
  • Compare the element at the center index with the element next to it:
    • If the center element is greater than the next element, adjust the right boundary to center.
    • Otherwise, move the left boundary to center + 1.
  • Return left as the index of the peak element once the loop exits.

This method efficiently finds a peak element in O(log n) time complexity due to the halving of the search interval with each iteration of the loop.

Comments

No comments yet.