Find Peak Element

Medium

Extra practice. This problem has no walkthrough slides. Try solving it with the pattern template on your own, and lean on 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 beyond both ends of the trail as being far below any reading, so 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 that sit right next to each other never share the same reading, and more than one peak can exist in the same trail. Any valid peak index is accepted.

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. Since the trail's start only has one neighbor, checkpoint 0 just needs to beat 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

Take a moment to understand the problem and think of your approach before you start coding.