ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Find Peak Element

Go

Goal -- WPM

Ready
Exercise Algorithm Area
1package main
2
3import "fmt"
4
5func findPeakElement(nums []int) int {
6 left, right := 0, len(nums)-1
7
8 for left < right {
9 mid := left + (right-left)/2
10 if nums[mid] > nums[mid+1] {
11 right = mid
12 } else {
13 left = mid + 1
14 }
15 }
16 return left
17}
18
19func main() {
20 nums1 := []int{1, 2, 3, 1}
21 fmt.Printf("Peak element in %v is at index: %d\n", nums1, findPeakElement(nums1))
22
23 nums2 := []int{1, 2, 1, 3, 5, 6, 4}
24 fmt.Printf("Peak element in %v is at index: %d\n", nums2, findPeakElement(nums2))
25
26 nums3 := []int{1}
27 fmt.Printf("Peak element in %v is at index: %d\n", nums3, findPeakElement(nums3))
28
29 nums4 := []int{3, 2, 1}
30 fmt.Printf("Peak element in %v is at index: %d\n", nums4, findPeakElement(nums4))
31}
Algorithm description viewbox

Find Peak Element

Algorithm description:

This function finds a peak element in an array. A peak element is an element that is strictly greater than its neighbors. The array can contain multiple peaks, and the function is guaranteed to find one of them. This is useful in scenarios like finding the maximum value in a unimodal array or in game theory simulations.

Algorithm explanation:

The algorithm uses binary search to efficiently find a peak element. The core idea is that if nums[mid] < nums[mid+1], then a peak must exist to the right of mid (including mid+1), so we discard the left half. Conversely, if nums[mid] > nums[mid+1], a peak must exist at or to the left of mid, so we discard the right half. The loop invariant is that a peak element is guaranteed to exist within the range [left, right]. The time complexity is O(log n) because we halve the search space in each iteration. The space complexity is O(1) as we only use a few variables. Edge cases like a single-element array are handled correctly as the loop condition `left < right` will not be met, and `left` (which is 0) will be returned, which is the peak.

Pseudocode:

function findPeakElement(nums):
  left = 0
  right = length(nums) - 1

  while left < right:
    mid = left + floor((right - left) / 2)
    if nums[mid] > nums[mid + 1]:
      right = mid
    else:
      left = mid + 1

  return left