Find Peak Element
MediumClimb toward the higher neighbour
A peak is bigger than both neighbors; always step toward the higher side and you'll climb to one.
The idea
If mid is on an upward slope the peak is to the right, otherwise to the left. Follow the ascent and you always converge on a peak.
1
2
1
3
5
6
4
0
1
2
3
4
5
6
Step 1 of 4. Brute force: scan for any element ≥ both of its neighbours. Values: 1, 2, 1, 3, 5, 6, 4.
1/4
Brute force
timeO(n)spaceO(1)
Scan for a peak.
1let peak = -1;2for (let i = 0; i < n && peak < 0; i++)3 if (nums[i] >= left && nums[i] >= right) peak = i;4return peak;Input
- array
- [1, 2, 1, 3, 5, 6, 4]
Memory
- i
- —
Output
- answer
- —
Check yourself
3 quick questions about this walkthrough. A wrong answer costs nothing.
Examples
Example 1
- Input:
- nums = [1, 2, 3, 1]
- Output:
- 2
- Explanation:
- 3 at index 2 is bigger than both neighbours.
Example 2
- Input:
- nums = [1, 2, 1, 3, 5, 6, 4]
- Output:
- 5
- Explanation:
- Index 5 (value 6) is a peak.
Example 3
- Input:
- nums = [1, 2, 3]
- Output:
- 2
- Explanation:
- The last, biggest element is a peak.
Practice this problem:LeetCode(opens in a new tab)Search GeeksforGeeks(opens in a new tab)
Finished the walkthrough? Add it to your streak.