Program to find local peak element indices from a list of numbers in Python

PythonServer Side ProgrammingProgramming

Suppose we have a list of numbers called nums whose length is at least 2. We have to find the index of every peak in the list. The list is sorted in ascending order. An index i is a peak when −

  • nums[i] > nums[i + 1] when i = 0

  • nums[i] > nums[i - 1] when i = n - 1

  • nums[i - 1] < nums[i] > nums[i + 1] else

So, if the input is like nums = [5, 6, 7, 6, 9], then the output will be [2, 4], as the element at index 2 is 7 which is larger than two neighbors, and item at index 4 is 9, this is larger than its left item.

To solve this, we will follow these steps −

  • ans := a new list

  • n := size of nums

  • if n is same as 1, then

    • return ans

  • for each index i and number num in nums, do

    • if i > 0 and i < n - 1, then

      • if nums[i - 1] < num > nums[i + 1], then

        • insert i at the end of ans

      • if i is same as 0, then

        • if num > nums[i + 1], then

          • insert i at the end of ans

      • if i is same as n - 1, then

        • if num > nums[i - 1], then

          • insert i at the end of ans

  • return ans

Example

Let us see the following implementation to get better understanding

def solve(nums):
   ans = []
   n = len(nums)

   if n == 1:
      return ans

   for i, num in enumerate(nums):
      if i > 0 and i < n - 1:
         if nums[i - 1] < num > nums[i + 1]:
            ans.append(i)

      if i == 0:
         if num > nums[i + 1]:
            ans.append(i)

      if i == n - 1:
         if num > nums[i - 1]:
            ans.append(i)

   return ans

nums = [5, 6, 7, 6, 9]
print(solve(nums))

Input

[5, 6, 7, 6, 9]

Output

[2, 4]
raja
Published on 11-Oct-2021 07:17:17
Advertisements