Find Peak Element in Array
Public Module PeakFinder ' Main function to find a peak element in an array. ' A peak element is an element that is strictly greater than its neighbors. ' If the array has multiple peaks, returning the index to any of the peaks is fine. Public Function FindPeakElement(ByVal nums(...
This algorithm finds a peak element in an array where a peak is defined as an element strictly greater than its neighbors. It uses a binary search approach to efficiently locate such an element. This is useful in scenari...
The `FindPeakElement` function implements a modified binary search to locate a peak element in an array. A peak element is guaranteed to exist because we can imagine that `nums[-1] = nums[n] = -infinity`. The algorithm iteratively narrows down the search space. If `nums[mid] < nums[mid + 1]`, it implies that a peak must exist to the right of `mid` (inclusive of `mid + 1`), so `left` is updated to `mid + 1`. Otherwise, if `nums[mid] >= nums[mid + 1]`, a peak must exist at `mid` or to its left, so `right` is updated to `mid`. The loop invariant is that a peak element is always present within the `[left, right]` range. The time complexity is O(log n) due to the binary search, and the space complexity is O(1) as it uses a constant amount of extra space. Edge cases like empty or single-element arrays are handled implicitly by the binary search logic and explicitly by an initial check.
Function FindPeakElement(array): If array is empty, throw error. Set left = 0, right = length of array - 1. While left < right: Calculate mid = left + (right - left) / 2. If array[mid] < array[mid + 1]: Set left = mid +...