FOR FREE MATERIALS

Peak Index

Back to Programming

Description

A peak element is an element that is greater than its neighbors.

Given an input array nums, where nums[i] ≠ nums[i + 1], find the peak elements and return the index.

The array may contain multiple peaks, in that case return the index of all peaks.

You may imagine that nums[-1] = nums[n] = - ∞

Example:

I/P: nums = [1, 2, 3, 1]

O/P: [2]

Explanation: 3 is a peak element and you function should return the index number 2

Algorithm

Example:

I/P: nums:= [1, 2, 1, 3, 5, 6, 4]

O/P = [1, 5]

Explanation: You function will return index numbers where the peak element is 2, and index number 5 where the peak element is 6.

Here the maximum value comes first at position 1 then again at position 5. So, [1, 5]

 

Example:

1

Here there is only one element so index is 0

ALGORITHM

Step 1: Create an array

Step 2: Check for the following conditions

  1. Whether the given array is empty or not. If empty return None
  2. If the length of the array is 1. Return the index
  3. If length of the array is greater than 1 go to Step 3

Step 3: Run a loop until the second last index is reached. 

           Check next element with the current element.

           i.e. nums[i + 1] <= nums[i]

           if true store it in the array

Step 4: Return the array

Code

Time Complexity:

Let the size of the given list is N

There is a loop till the second last element

So, O(N – 1) which is O(N)

Space Complexity:

For creating a list to store the index

So, O(N) when all the values are equal in the given list