Stack implementation:
class Stack:
def pop(self):
return self.items.pop()
def __init__(self):
self.items = []
def push(self, item):
return self.items.append(item)
def size(self):
return len(self.items)
def peek(self):
return self.items[len(self.items)-1]
def isEmpty(self):
return len(self.items) == 0
Code for given problem
def ngr(arr):
result = Stack()
stack = Stack()
for elem in arr[::-1]:
if not stack.isEmpty() and stack.peek() < elem:
while not stack.isEmpty() and stack.peek() <= elem:
stack.pop()
if not stack.isEmpty() and stack.peek() > elem:
result.push(stack.peek())
if stack.isEmpty():
result.push(-1)
stack.push(elem)
print(arr)
print(result.items[::-1])
ngr([0,1, 3, 2, 4])
# output
# [0, 1, 3, 2, 4]
# [1, 3, 4, 4, -1]
Like this:
Like Loading...