Intermediate Level

Implement the findPeakElementIndex method that returns an index of a peak element in the array.

The input contains an integer array nums and its length size. Your task is to return the index of a peak element.

A peak element is greater than its neighbor values. The first element can be a peak if it is greater than the next value, and the last element can be a peak if it is greater than the previous value. For example, in [1,3,2], index 1 is the peak.

Example 1

Input
nums (int[]) = [1,3,2]
size (int) = 3
Returns (int) 1

Example 2

Input
nums (int[]) = [5,4,3]
size (int) = 3
Returns (int) 0

Example 3

Input
nums (int[]) = [1,2,3]
size (int) = 3
Returns (int) 2

Check each position and compare it with its available neighbors.

For the first element, only compare it with the next element. For the last element, only compare it with the previous element. For middle elements, both left and right neighbors must be smaller.

Return the first index that satisfies the peak condition. If the array is empty, return -1.

Pseudocode:

function findPeakElementIndex(nums, size):
    if size == 0:
        return -1
    for i from 0 to size - 1:
        leftOk = i == 0 or nums[i] > nums[i - 1]
        rightOk = i == size - 1 or nums[i] > nums[i + 1]
        if leftOk and rightOk:
            return i
    return -1
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.