- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

Suppose we have a list of numbers called nums. We have to find the index of every peak element in the nums, sorted in ascending order. An index i of a peak element when all of these three conditions are satisfied: 1. The next number on its right that's different than nums[i] doesn't present or must be smaller than nums[i] 2. The previous number on its left that's different than nums[i] doesn't present or must be smaller than nums[i] 3. There is at least one number on its left side or right side that is different from nums[i].

So, if the input is like nums = [5, 8, 8, 8, 6, 11, 11], then the output will be [1, 2, 3, 5, 6], because the plateau of 8s are considered as peaks [1,2,3]. And 11s are also, [5, 6].

To solve this, we will follow these steps −

- n := size of nums
- ans := a new list
- i := 0
- while i < n, do
- i0 := i
- while i < n and nums[i] is same as nums[i0], do
- i := i + 1

- if (i0 is 0 or nums[i0] > nums[i0 - 1]) and (i is n or nums[i0] > nums[i]), then
- if i0 is not 0 or i is not n, then
- insert a (list from i0 to i-1) at the end of ans

- if i0 is not 0 or i is not n, then

- return ans

Let us see the following implementation to get better understanding −

def solve(nums): n = len(nums) ans = [] i = 0 while i < n: i0 = i while i < n and nums[i] == nums[i0]: i += 1 if (i0 == 0 or nums[i0] > nums[i0 - 1]) and (i == n or nums[i0] > nums[i]): if i0 != 0 or i != n: ans.extend(range(i0, i)) return ans nums = [5, 8, 8, 8, 6, 11, 11] print(solve(nums))

[5, 8, 8, 8, 6, 11, 11]

[1, 2, 3, 5, 6]

- Related Questions & Answers
- Program to find local peak element indices from a list of numbers in Python
- Python Program – Print the count of either peaks or valleys from a list
- Python program to find number of local variables in a function
- Python - Ways to find indices of value in list
- Program to find minimum possible difference of indices of adjacent elements in Python
- Python Program to repeat elements at custom indices
- Program to shuffle string with given indices in Python
- Python program to remove elements at Indices in List
- Find elements of a list by indices in Python
- Program to check number of global and local inversions are same or not in Python
- Program to find start indices of all anagrams of a string S in T in Python
- Find indices with None values in given list in Python
- Python Program to get indices of sign change in a list
- Get match indices in Python
- Find all good indices in the given Array in Python\n

Advertisements