- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to find circular greater element to the right in Python
Suppose we have a list of numbers called nums. We have to find a new list of the same length where the value at index i is assigned to the next element greater than nums[i] to its right, circling back to the front of the list when required. If there is no number that is greater, then it should be set to -1.
So, if the input is like [4, 5, 1, 3], then the output will be [5, -1, 3, 4]
To solve this, we will follow these steps−
n := size of a
stack := a stack, insert 0 initially, res := a list of size n and fill with -1
for each value in range 0 and 1, do
for i in range 0 to n-1, do
while stack is not empty and a[top of stack] < a[i], do
res[top of stack] := a[i]
delete last element from stack
insert i at the end of stack
return res
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, a): n = len(a) stack, res = [0], [-1] * n for _ in range(2): for i in range(n): while stack and a[stack[-1]] < a[i]: res[stack[-1]] = a[i] stack.pop() stack.append(i) return res ob = Solution() nums = [4, 5, 1, 3] print(ob.solve(nums))
Input
[4, 5, 1, 3]
Output
[5, -1, 3, 4]
- Related Articles
- Next Greater Element in Circular Array in JavaScript
- Python program to search an element in a Circular Linked List
- Program to find the maximum sum of circular sublist in Python
- Find smallest element greater than K in Python
- Program to find ith element by rotating k times to right
- Program to find length of longest circular increasing subsequence in python
- Python Program to find the largest element in an array
- Program to find most visited sector in a circular track using Python
- Replace every element with the least greater element on its right using C++
- Python Program to find largest element in an array
- Program to find minimum distance to the target element using Python
- Python Program to find the Next Nearest element in a Matrix
- Program to find frequency of the most frequent element in Python
- Python Program to find the cube of each list element
- Program to find lowest sum of pairs greater than given target in Python
