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]