LeetCode #162: Find Peak Element — Always Walk Uphill
Brute To Best
0:00 / 0:00
LeetCode #162: Find Peak Element — Always Walk Uphill
0 просмотров · 12 дней назад
Brute To Best
59 подписчиков
0 просмотров · 12 дней назад
Problem #162 of the Brute To Best series: Find Peak Element.
Return the index of any element strictly greater than both its neighbours, in O(log n). The array is not sorted, which makes binary search look impossible, but the slope at the midpoint always points toward a peak.
In this video:
What counts as a peak, and why the ends are treated as negative infinity Why any peak is acceptable, not the largest one The linear scan: find the first index where the values stop rising Why the O(log n) requirement rules that out Why binary search works without sortedness The comparison: nums[mid] against nums[mid plus 1] When the next value is larger, a peak must exist to the right When it is smaller, mid itself could be the peak, so keep it Why left equals mid plus 1 and right equals mid are the correct moves Why the loop condition is left less than right with no equality branch Why the invariant guarantees a peak is always inside the range Handling a single element, and a strictly increasing array Dry run with [1,2,1,3,5,6,4] reaching index 5 Time O(log n), space O(1)
LeetCode 162 — Find Peak Element: https://leetcode.com/problems/find-pe...
Peak Index in a Mountain Array is the guaranteed-single-peak version, and Find a Peak Element II runs the same idea over a grid.
Earlier in the series: problems #1 to #161, in order.
Subscribe to Brute To Best — every problem, from the brute force to the best solution.
#leetcode #findpeakelement #binarysearch #arrays #divideandconquer #peakfinding #dsa #coding #codinginterview #problemsolving #datastructuresandalgorithms #leetcodesolutions #brutetobest #mediumproblems