Search for a command to run...
Try your own input
Change the array and replay the algorithm from step one.
Current step
A peak is any element bigger than both neighbours. The array is not sorted, yet binary search still applies: an upward slope at mid guarantees a peak somewhere to the right, and a downward slope guarantees one to the left — so half can always be discarded.
Binary Search on Slope
1function findPeakElement(arr) {2 const n = arr.length;//n: 103 4 // Edge cases5 if (n == 1) return 0;6 if (arr[0] > arr[1]) return 0;7 if (arr[n - 1] > arr[n - 2]) return n - 1;8 9 let low = 1, high = n - 2;10 while (low <= high) {11 const mid = Math.floor((low + high) / 2);12 13 // Bigger than both neighbours14 if (arr[mid - 1] < arr[mid] && arr[mid] > arr[mid + 1])15 return mid;16 17 // Descending into mid — climb left18 if (arr[mid] < arr[mid - 1])19 high = mid - 1;20 // Still ascending — climb right21 else22 low = mid + 1;23 }24 return -1;25}