Find Peak Element

Medium

This is an extra practice problem. It doesn't have walkthrough slides. You can solve it with the pattern template you already know. Open the hints if you get stuck.

Question

You're monitoring elevation readings taken at evenly spaced checkpoints along a hiking trail. A checkpoint is a peak if its reading is strictly higher than the checkpoints immediately next to it. Treat the ground past both ends of the trail as lower than any reading. That means the very first or very last checkpoint can also count as a peak.

Given a list of elevation readings, return the index of any one peak checkpoint.

Note: Two checkpoints right next to each other never have the same reading. A trail can also have more than one peak. You can return the index of any of them.

Input: nums = [1, 3, 5, 4, 2]

Output: 2

Checkpoint 2 has a reading of 5, which is higher than both of its neighbors (3 and 4).

Input: nums = [9, 5, 3, 1]

Output: 0

Checkpoint 0 has a reading of 9. The first checkpoint only has one neighbor. So checkpoint 0 just needs to be higher than checkpoint 1 to count as a peak.

Input: nums = [1, 5, 2, 8, 3]

Output: 1 or 3

Checkpoint 1 (reading 5) and checkpoint 3 (reading 8) are both peaks. Either index is a correct answer.

Clarify the problem

What are some questions you'd ask an interviewer?

Understand the problem

Given nums = [4, 8, 2, 9, 6], which of these indices is a valid peak to return?
0
1
2
4

Remember to understand the problem and plan your approach before you start coding.