Taro Logo

Find Peak Element

Medium
Asked by:
Profile picture
Profile picture
Profile picture
Profile picture
+23
More companies
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
1.6K views
Topics:
ArraysBinary Search

A peak element is an element that is strictly greater than its neighbors.

Given a 0-indexed integer array nums, find a peak element, and return its index. If the array contains multiple peaks, return the index to any of the peaks.

You may imagine that nums[-1] = nums[n] = -∞. In other words, an element is always considered to be strictly greater than a neighbor that is outside the array.

You must write an algorithm that runs in O(log n) time.

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.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. How should we handle boundary elements like the first and last elements of the array—do we assume they are greater than implicit elements outside the array (such as negative infinity), or is there a specific wrapping behavior?
  2. Can the array contain duplicate adjacent values, and if so, how does that affect the definition of strictly greater than neighbors?
  3. What should be returned if the input array is empty or null?
  4. If the array contains multiple peak elements, does it matter which peak's index I return, or is returning any valid peak index acceptable?
  5. Can I assume the array always contains at least one peak element under the problem's constraints?

Brute Force Solution

Approach

Imagine you are looking at a line of hills of different heights and need to find a hill that is higher than its immediate neighbors. The brute force approach involves walking down the entire line and checking each hill one by one to see if it fits the requirement.

Here's how the algorithm would work step-by-step:

  1. Start at the very beginning of the line of hills.
  2. Look at the first hill and check if it is taller than the hill next to it.
  3. If it is not taller, take one step forward to the next hill in line.
  4. Compare the height of this current hill with both the hill to its left and the hill to its right.
  5. If the current hill is taller than both of its neighbors, you have found a peak and you can stop searching.
  6. If it is not a peak, continue walking forward and repeating the neighbor comparison for every single hill.
  7. Keep doing this until you check every single hill until you reach the end of the line.

Code Implementation

def find_peak_element(hill_heights):    total_hills = len(hill_heights)        # Check every hill sequentially because brute force requires inspecting each element    for current_index in range(total_hills):        left_is_lower = current_index == 0 or hill_heights[current_index] > hill_heights[current_index - 1]        right_is_lower = current_index == total_hills - 1 or hill_heights[current_index] > hill_heights[current_index + 1]                # Stop immediately when we find a hill taller than both immediate neighbors        if left_is_lower and right_is_lower:            return current_index                # Fallback return in case no peak condition is met during traversal    return 0

Big(O) Analysis

Time Complexity
O(n) – The input size is n representing the total number of hills in the array. The cost is driven by walking through the entire line and checking each hill one by one. In the worst case, we must visit every single hill to find a peak or reach the end of the line. This requires checking each of the n elements sequentially. Therefore, the total operations approximate n steps, which simplifies to O(n).
Space Complexity
O(1) – The brute force approach described only utilizes a few primitive pointer variables to keep track of the current position in the line of hills. No additional auxiliary data structures such as temporary lists, hash maps, or recursive call stacks are created during the traversal. Regardless of the input size N, the extra memory consumed by these tracking variables remains constant. Therefore, the auxiliary space complexity simplifies to Big O of 1.

Optimal Solution

Approach

Instead of checking every single item one by one, the optimal approach uses a smart guessing strategy similar to finding a word in a dictionary by constantly cutting the search area in half. By looking at the immediate neighbors of a chosen spot, we can always guarantee that at least one peak is hiding on the side that goes uphill.

Here's how the algorithm would work step-by-step:

  1. Begin by looking at the item sitting right in the middle of the entire group.
  2. Check the item immediately to the right of your current position.
  3. If the item to the right is taller than the one you are currently looking at, you know for a fact that a peak must exist somewhere on the right-hand side because the ground is sloping upward in that direction.
  4. If the item to the right is shorter, you know a peak must exist somewhere on the left-hand side because the ground is sloping downward.
  5. Throw away the half of the group where the peak cannot possibly be, cutting your search area directly in half.
  6. Repeat this process of checking the middle and discarding the losing half until you have zeroed in on a spot that is higher than both of its immediate neighbors.
  7. Claim this final spot as your peak and finish the search efficiently without ever having to look at most of the items.

Code Implementation

def find_peak_element(integer_array):
    left_boundary = 0
    right_boundary = len(integer_array) - 1

    while left_boundary < right_boundary:
        middle_index = (left_boundary + right_boundary) // 2

        # Compare middle element with its right neighbor to determine the slope direction.
        if integer_array[middle_index] < integer_array[middle_index + 1]:

            left_boundary = middle_index + 1
        else:

            right_boundary = middle_index

    # The search space converges to a single index representing a valid peak element.
    return left_boundary

Big(O) Analysis

Time Complexity
O(log n) – Instead of examining every item in the array of size n, the algorithm repeatedly compares the middle element to its right neighbor and discards half of the search space. By cutting the remaining elements in half at each step, the search process requires a logarithmic number of divisions. This halves the search space repeatedly, leading to approximately log base 2 of n operations. Simplifying this process yields a final time complexity of O(log n).
Space Complexity
O(1) – The algorithm relies entirely on an iterative binary search approach using a fixed number of pointer variables to track indices such as left, right, and middle. No auxiliary data structures, temporary lists, or recursive stack frames are created during the execution. Because the amount of extra memory remains constant regardless of the input size N, the auxiliary space complexity is strictly O(1).

Edge Cases

Single-element array
How to Handle:
Return index zero immediately since the sole element is trivially greater than its out-of-bounds imaginary negative infinity neighbors.
Two-element strictly increasing or decreasing array
How to Handle:
Binary search correctly identifies the boundary element as the peak by comparing the two values and following the slope.
Array sorted in strictly ascending order
How to Handle:
The binary search naturally migrates to the right boundary, correctly identifying the final element as a peak.
Array sorted in strictly descending order
How to Handle:
The binary search migrates to the left boundary, correctly identifying the first element as a peak.
Array with multiple peaks
How to Handle:
Binary search guarantees finding at least one valid peak by moving toward whichever neighbor is strictly greater.
Array containing negative numbers and zeros
How to Handle:
The relative greater-than comparisons function identically across negative and positive domains without requiring offset adjustments.
Maximum-sized inputs up to constraints limit
How to Handle:
O(log n) binary search executes efficiently within logarithmic time and constant O(1) space, avoiding memory limits.
Midpoint calculation with extreme array lengths
How to Handle:
Using the bitwise shift or low plus high minus low divided by two prevents potential integer overflow during index addition.
0/75 completed