15% off all plans & roadmaps Use code

See plans

Find Peak Element

Updated

TL;DR: Find any index whose value is greater than both neighbors, in O(log n) time. Binary search works because the slope between mid and mid + 1 tells you which half must contain a peak.

Problem

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 has several peaks, return the index of any one of them.

You may treat nums[-1] and nums[n] as negative infinity. An element at either end is therefore greater than its missing neighbor.

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
  • -2^31 <= nums[i] <= 2^31 - 1
  • nums[i] != nums[i + 1] for all valid i.

Constraints that matter

  • n <= 1000 makes an O(n) scan fast in practice, but the statement requires O(log n), so a linear scan does not meet the stated requirement.
  • Values span the full 32-bit range, so do not use -1 or INT_MIN as a stand-in for negative infinity. Check the array boundaries directly instead.
  • Adjacent values are never equal, so nums[mid] < nums[mid + 1] always gives a clear answer. Equal neighbors would leave the slope undefined.
  • The array is not sorted. Only local slopes matter, so the solution must rely on a slope test and not on global order.

View on LeetCode

Hints

Hint 1

The problem looks like a search for the maximum, but you do not need the global maximum.

Hint 2

The naive solution checks each index against its neighbors and returns the first index greater than both.

Solution

Intuition

The problem looks like a search for the maximum, but you do not need the global maximum. You need any spot where the values stop rising. That spot is a local maximum, and the boundary rule guarantees that one exists.

Picture walking across a foggy field, checking only whether the ground rises or falls under your next step. If it rises, the highest point lies ahead, so you never walk back. The slope test at mid is that step, and the discarded half is the ground you no longer check.

This is a binary search. Look at mid and its right neighbor. If the value rises from mid to mid + 1, a peak must sit to the right, because the values cannot rise forever inside a finite array. If the value falls, a peak sits at mid or to the left.

Each probe discards about half the window, so the search needs about log2(n) probes. A binary search does not need sorted data. It needs one test that proves which half is safe to drop, and the slope test is that test.

Watch the pattern animation

Worked example

Input: nums = [10, 20, 15, 2, 23, 90, 67]
Output: 5
Explanation: The value 90 at index 5 is greater than its left neighbor 23 and its right neighbor 67, so index 5 is a peak. Index 1 (value 20) is also a peak, so 1 would be a valid answer too. The page's solutions return 5.

Approach 1: Linear scan from the right

The naive solution checks each index against its neighbors and returns the first index greater than both. Missing neighbors count as negative infinity, so the ends are handled by boundary checks.

The slow part is that the scan can read every element before it finds a peak. A strictly decreasing array such as [5,4,3,2,1] has its only peak at index 0, so the scan reads all n values. The statement demands O(log n), so this approach is too slow for the stated bound.

This version walks from the right end. On the verified example it stops at index 5. Walking from the left would stop at index 1, which is also a valid peak.

Steps

  1. Set i to n - 1 and walk down to 0.
  2. At each i, the left check passes when i is 0 or nums[i] > nums[i - 1].
  3. The right check passes when i is n - 1 or nums[i] > nums[i + 1].
  4. Return i as soon as both checks pass.
  5. Return -1 after the loop as a guard. For n >= 1 a peak always exists, so the loop returns first.

Dry run

Start at i = 6, where the value is 67. Its left neighbor 90 is larger, so the left check fails.

At i = 5 the value is 90. Its left neighbor 23 is smaller, and its right neighbor 67 is smaller. Both checks pass, so the function returns 5.

The trace reads only 2 of the 7 values. The worst case reads all of them, as the decreasing array above shows.

Complexity

TimeO(n)
SpaceO(1)

Let n be the length of nums. The loop runs at most n times, and each pass does two comparisons and a few index checks, which is constant work. The total work is therefore at most a fixed constant times n, which gives O(n). The scan keeps only the index and two booleans, so the extra space is O(1).

PythonTested in our runner

class Solution:
    def findPeakElement(self, nums: List[int]) -> int:
        n = len(nums)
        # Walk from the right so the verified example returns 5
        for i in range(n - 1, -1, -1):
            left_ok = i == 0 or nums[i] > nums[i - 1]
            right_ok = i == n - 1 or nums[i] > nums[i + 1]
            if left_ok and right_ok:
                return i
        return -1

The Find Min/Max in Rotated Sorted Array infographic is part of Pro

A one-page visual of the pattern: when it applies, the steps and the invariant to keep.

Unlock the infographic

Solution pattern

Find Min/Max in Rotated Sorted Array

Part of Binary Search Patterns

Approach 2: Binary search on the slopeOptimalFind Min/Max in Rotated Sorted Array

What is slow in the linear scan is that it examines values that cannot change the answer. One comparison at mid can rule out half of the window. If nums[mid] < nums[mid + 1], the values rise at mid, so a peak lies in [mid + 1, right]. If nums[mid] > nums[mid + 1], the values fall at mid, so a peak lies in [left, mid].

The proof rests on an invariant. The value at left is greater than its left neighbor, or left is 0. The value at right is greater than its right neighbor, or right is n - 1. Both hold at the start, because the ends see negative infinity.

The update left = mid + 1 keeps the invariant because nums[mid + 1] > nums[mid]. The update right = mid keeps it because nums[mid] > nums[mid + 1].

With the invariant, a peak must exist in the window. Take the first index k in the window where nums[k] > nums[k + 1]. It exists because right qualifies. The index k is a peak, because every earlier index rises into it and the first step is covered by the left-end invariant.

Why it is correct. The window keeps a rising edge on its left and a falling edge on its right, so a peak must lie between them. Each update drops a half only when the slope at mid shows a peak remains in the half that is kept. When the window shrinks to one index, the invariant forces that index to be a peak.

Steps

  1. Set left to 0 and right to n - 1.
  2. While left < right, compute mid = left + (right - left) / 2.
  3. If nums[mid] < nums[mid + 1], set left = mid + 1.
  4. Otherwise set right = mid.
  5. When the loop ends, left equals right. Return left.

Dry run

The table traces the verified example [10, 20, 15, 2, 23, 90, 67].

Stepleftrightmidnums[mid]nums[mid + 1]Action
10632232 < 23, so left = 4
2465906790 > 67, so right = 5
3454239023 < 90, so left = 5
455---left equals right, stop

The loop ends with left = right = 5. Index 5 holds 90, which is greater than both 23 and 67, so the function returns 5.

Complexity

TimeO(log n)
SpaceO(1)

Let n be the array length and s the current window size, which is right - left + 1. A pass keeps either the part after mid or the part up to mid, and each part has at most ceil(s / 2) elements. After k passes the window has at most ceil(n / 2^k) elements, so the loop ends after about log2(n) passes.

Each pass does constant work, so time is O(log n). The solution stores only left, right and mid, so space is O(1).

PythonTested in our runner

class Solution:
    def findPeakElement(self, nums: List[int]) -> int:
        left, right = 0, len(nums) - 1
        # Invariant: a peak lies in nums[left..right]
        while left < right:
            mid = left + (right - left) // 2
            if nums[mid] < nums[mid + 1]:
                # Rising at mid, so a peak lies to the right
                left = mid + 1
            else:
                # Falling at mid, so mid or a point to its left is a peak
                right = mid
        return left

Common mistakes

  • Using while left <= right with right = mid - 1. The step right = mid - 1 can skip mid, which may be the only peak. Keep while left < right and right = mid, so the window always contains a peak.
  • Swapping the branches, so the code sets left = mid + 1 when nums[mid] > nums[mid + 1]. A falling slope means the peak is at mid or to the left. Move right only on a rising slope.
  • Reading nums[mid + 1] when mid is n - 1. This happens when the loop condition is left <= right. Keep left < right, which keeps mid below right.
  • Checking nums[i] > nums[i + 1] in the linear scan at i = n - 1. That index does not exist. Treat a missing neighbor as negative infinity with an explicit boundary check.
  • Returning nums[left] when the function must return an index. The value 90 is not the index 5. Return left for this signature, and return the value only in the follow-up.

Edge cases

  • A single element [7]. The loop never runs, and the function returns 0.
  • Two elements [1,2] return 1, and [2,1] returns 0. Each element is checked against the outside negative infinity.
  • A strictly increasing array [1,2,3,4] returns 3, and a strictly decreasing array [4,3,2,1] returns 0.
  • Extreme values [-2147483648,-2147483647] return 1. The comparisons work without sentinel arithmetic, so no overflow occurs.
  • Several peaks [1,3,2,4,3] can return either 1 or 3. Both answers are correct, and the tests accept either.

Follow-ups interviewers ask

What if the function must return the peak value instead of the index?
Return nums[left] after the loop. Both left and right name the final peak, so the value comes from the same position and no extra scan is needed.
Can you sort the array to find a peak?
Sort the indices by value in descending order. The first index is the global maximum, and it is a peak because both neighbors are strictly smaller. Sorting costs O(n log n) time and O(n) space for the index array, which misses the O(log n) bound.
What if equal neighbors are allowed?
A strict peak may not exist, as in [2,2,2]. The same loop still returns an index that is greater than or equal to both neighbors. The earlier invariant still holds, so the window always contains such an index.

Find Peak Element FAQ

What is the time complexity of Find Peak Element?

The binary search version runs in O(log n) time, which the statement requires. The linear scan runs in O(n) time. Both use O(1) extra space.

Why use binary search for Find Peak Element?

The array is not sorted, but one comparison of nums[mid] and nums[mid + 1] tells you which half must contain a peak. That test lets each step discard half the window, which gives the logarithmic bound.

Can Find Peak Element be solved in O(1) extra space?

Yes. The binary search stores only left, right and mid. The linear scan stores only an index and two booleans. Neither solution needs a map, a stack or a copy of the array.

Does binary search on this problem need the array to be sorted?

No. The loop never checks global order. It relies on local slopes and on the rule that values outside the array count as negative infinity.

Why does the binary search return left and not mid?

The loop ends when left equals right, so both name the same index. Returning left matches the state after the last update and avoids an extra variable.

Asked at

See which companies ask this — Pro

Practise it