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

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

Find Peak Element

C++

Goal -- WPM

Ready
Exercise Algorithm Area
1#include <vector>
2#include <iostream>
3
4// Helper function to check if an element is a peak
5bool isPeak(const std::vector<int>& nums, int index) {
6int n = nums.size();
7if (index < 0 || index >= n) {
8return false; // Out of bounds
9}
10// Check left neighbor
11if (index > 0 && nums[index] <= nums[index - 1]) {
12return false;
13}
14// Check right neighbor
15if (index < n - 1 && nums[index] <= nums[index + 1]) {
16return false;
17}
18return true;
19}
20
21// Function to find a peak element using binary search
22int findPeakElement(const std::vector<int>& nums) {
23int n = nums.size();
24
25// Handle edge case: empty array
26if (n == 0) {
27return -1; // Or throw an exception
28}
29
30// Handle edge case: single element array
31if (n == 1) {
32return 0;
33}
34
35int left = 0;
36int right = n - 1;
37
38while (left < right) {
39int mid = left + (right - left) / 2;
40
41// If mid element is greater than its right neighbor, a peak must be in the left half (including mid)
42if (nums[mid] > nums[mid + 1]) {
43right = mid;
44} else {
45// If mid element is less than or equal to its right neighbor, a peak must be in the right half (excluding mid)
46left = mid + 1;
47}
48}
49
50// When the loop terminates, left == right, and this is a peak element
51return left;
52}
53
54int main() {
55std::vector<int> nums1 = {1, 2, 3, 1};
56std::cout << "Peak element in {1, 2, 3, 1}: " << findPeakElement(nums1) << std::endl;
57
58std::vector<int> nums2 = {1, 2, 1, 3, 5, 6, 4};
59std::cout << "Peak element in {1, 2, 1, 3, 5, 6, 4}: " << findPeakElement(nums2) << std::endl;
60
61std::vector<int> nums3 = {1};
62std::cout << "Peak element in {1}: " << findPeakElement(nums3) << std::endl;
63
64std::vector<int> nums4 = {3, 2, 1};
65std::cout << "Peak element in {3, 2, 1}: " << findPeakElement(nums4) << std::endl;
66
67std::vector<int> nums5 = {1, 2, 3};
68std::cout << "Peak element in {1, 2, 3}: " << findPeakElement(nums5) << std::endl;
69
70return 0;
71}
Algorithm description viewbox

Find Peak Element

Algorithm description:

This C++ code finds a peak element in an array. A peak element is defined as an element that is strictly greater than its adjacent neighbors. The algorithm utilizes binary search to efficiently locate such an element. This is useful in scenarios where you need to find a local maximum in data, such as in signal processing or optimization problems.

Algorithm explanation:

The `findPeakElement` function implements a binary search approach to find a peak element in a given array `nums`. A peak element is strictly greater than its neighbors. The algorithm handles edge cases such as empty or single-element arrays. The core logic relies on the observation that if `nums[mid] > nums[mid + 1]`, a peak must exist in the left half (including `mid`), otherwise, a peak must exist in the right half (excluding `mid`). The loop invariant is that a peak element is guaranteed to exist within the range `[left, right]`. The time complexity is O(log n) due to binary search, and the space complexity is O(1) as it uses a constant amount of extra space. The correctness is ensured by the monotonic property exploited by binary search: we always move towards a direction where a peak is guaranteed to exist.

Pseudocode:

function findPeakElement(nums):
  n = length of nums
  if n is 0:
    return -1
  if n is 1:
    return 0

  left = 0
  right = n - 1

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

  return left