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

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

Find Peak Element in Array

Visual Basic .NET

Goal -- WPM

Ready
Exercise Algorithm Area
1Public Module PeakFinder
2
3' Finds a peak element in an array. A peak element is an element that is strictly greater than its neighbors.
4' If the array contains multiple peaks, returning any peak is fine.
5' Assume nums[-1] = nums[n] = -infinity.
6Public Function FindPeakElement(ByVal nums() As Integer) As Integer
7If nums Is Nothing OrElse nums.Length = 0 Then
8Throw New ArgumentException("Input array cannot be null or empty.")
9End If
10
11Dim n As Integer = nums.Length
12
13' Handle the edge case of a single element array
14If n = 1 Then
15Return 0
16End If
17
18' Check if the first element is a peak
19If nums(0) > nums(1) Then
20Return 0
21End If
22
23' Check if the last element is a peak
24If nums(n - 1) > nums(n - 2) Then
25Return n - 1
26End If
27
28' Use binary search to find a peak element
29Dim left As Integer = 1
30Dim right As Integer = n - 2
31
32While left <= right
33Dim mid As Integer = left + (right - left) \\ 2 ' Integer division to prevent overflow
34
35' Check if mid is a peak
36If nums(mid) > nums(mid - 1) AndAlso nums(mid) > nums(mid + 1) Then
37Return mid
38Else If nums(mid) < nums(mid + 1) Then
39' If the element to the right is greater, a peak must be on the right side
40left = mid + 1
41Else
42' If the element to the left is greater, a peak must be on the left side
43right = mid - 1
44End If
45End While
46
47' This part should theoretically not be reached if the problem guarantees a peak exists.
48' However, for completeness, we can return -1 or throw an exception.
49' Based on the problem constraints (nums[-1] = nums[n] = -infinity), a peak always exists.
50Return -1 ' Should not happen given problem constraints
51End Function
52
53' Helper function to check if an element is a peak
54' This is illustrative; the main logic directly checks neighbors.
55Private Function IsPeak(ByVal arr() As Integer, ByVal index As Integer) As Boolean
56Dim n As Integer = arr.Length
57If index < 0 OrElse index >= n Then
58Return False
59End If
60
61Dim leftNeighbor As Integer = If(index = 0, Integer.MinValue, arr(index - 1))
62Dim rightNeighbor As Integer = If(index = n - 1, Integer.MinValue, arr(index + 1))
63
64Return arr(index) > leftNeighbor AndAlso arr(index) > rightNeighbor
65End Function
66
67End Module
Algorithm description viewbox

Find Peak Element in Array

Algorithm description:

This algorithm finds a peak element in an array where a peak is defined as an element strictly greater than its neighbors. The problem statement often assumes that the elements at indices -1 and n (where n is the array length) are negative infinity, guaranteeing at least one peak exists. A common application is in optimization problems where finding a local maximum is a step towards a global solution, or in scenarios where data exhibits local maxima like signal processing or financial data analysis.

Algorithm explanation:

The `FindPeakElement` function utilizes a binary search approach to efficiently locate a peak element. The time complexity is O(log n) because the search space is halved in each iteration. The space complexity is O(1) as it only uses a few variables for indices and does not require additional data structures. Edge cases such as empty or single-element arrays are handled. The algorithm also explicitly checks the boundaries of the array to see if the first or last elements are peaks. The core logic relies on the observation that if an element is not a peak, then at least one of its neighbors must be greater. By moving towards the greater neighbor, we are guaranteed to eventually find a peak. The invariant maintained is that a peak element must exist within the current search range [left, right].

Pseudocode:

function findPeakElement(nums):
  if nums is empty or null:
    throw error
  n = length of nums
  if n == 1:
    return 0
  if nums[0] > nums[1]:
    return 0
  if nums[n-1] > nums[n-2]:
    return n-1
  left = 1
  right = n-2
  while left <= right:
    mid = left + (right - left) / 2
    if nums[mid] > nums[mid-1] and nums[mid] > nums[mid+1]:
      return mid
    else if nums[mid] < nums[mid+1]:
      left = mid + 1
    else:
      right = mid - 1
  return -1 // Should not be reached