THN Interview Prep

162. Find Peak Element

At a Glance

  • Topic: binary-search
  • Pattern: Binary Search (Slope / neighbor compare)
  • Difficulty: Medium
  • Companies: Google, Amazon, Meta, Apple, Bloomberg
  • Frequency: High
  • LeetCode: 162

Problem (one-liner)

Given an array where nums[-1] and nums[n] are treated as negative infinity, return any index that is a strict local peak (nums[index] > neighbors). Guarantee a peak exists.

Recognition Cues

  • “Peak” with boundaries at negative infinity
  • O(log n) expected
  • Compare mid to mid+1 to see uphill vs downhill

Diagram

At-a-glance flow (replace with problem-specific Mermaid as you refine this note). camelCase node IDs; no spaces in IDs.

Loading diagram…

Approaches

  • Brute forceO(n) — scan for nums[index] > nums[index+1] and nums[index] > nums[index-1].
  • Better — not needed.
  • OptimalO(log n) time / O(1) space — if nums[mid] < nums[mid+1], a peak exists to the right; else to the left (inclusive mid).

Optimal Solution

Go

func findPeakElement(nums []int) int {
	left, right := 0, len(nums)-1
	for left < right {
		mid := left + (right-left)/2
		if nums[mid] < nums[mid+1] {
			left = mid + 1
		} else {
			right = mid
		}
	}
	return left
}

JavaScript

function findPeakElement(nums) {
	let left = 0;
	let right = nums.length - 1;
	while (left < right) {
		const mid = left + Math.floor((right - left) / 2);
		if (nums[mid] < nums[mid + 1]) {
			left = mid + 1;
		} else {
			right = mid;
		}
	}
	return left;
}

Walkthrough

nums = [1,2,3,1]

stepleftrightmidnums[mid] vs nums[mid+1]move
10312 < 3left = 2
22323 > 1right = 2

Return index 2. Invariant: a peak always remains in [left, right].

Edge Cases

  • Single element — peak index 0.
  • Strictly increasing — peak at last index.
  • Strictly decreasing — peak at index 0.

Pitfalls

  • Off-by-one comparing mid to mid-1 only — need consistent uphill rule with mid+1.
  • Assuming unique peak — any peak is acceptable.

Similar Problems

Variants

  • 2D peak — compare to four neighbors; move toward larger neighbor.
  • Bitonic array peak — known structure; similar slope logic.

Mind-Map Tags

#binary-search #peak #slope #neighbor-compare

Last updated on

Spotted something unclear or wrong on this page?

On this page