# Python program to print next smaller to right using Brute-force approach (using nested loops)
def nearest_smaller_to_right(arr):
result = []
for i in range(0, len(arr)):
for j in range(i+1,len(arr)):
if arr[i] > arr[j]:
result.append(arr[j])
break
else:
result.append(-1)
return result
arr = [11, 6, 42, 65, 32, 54]
print(nearest_smaller_to_right(arr))
# Python program to print next smaller to right element using stack
from collections import deque
#class to create stack and basic operations on stack
class Stack:
def __init__(self):
self.stack = deque() #can take list also like self.stack=[]
def push(self,data):
self.stack.append(data)
def pop(self):
if self.is_empty():
raise Exception('Stack Underflow')
return self.stack.pop()
def peek(self):
if self.is_empty():
return None
return self.stack[-1]
def is_empty(self):
return len(self.stack)==0
def size(self):
return len(self.stack)
#function to print next smaller to right element using stack
def nearest_smaller_to_right(arr):
#making object of Stack class
stack = Stack()
result = []
#start traversing from last element
for i in range(len(arr)-1,-1,-1):
if stack.is_empty():
result.append(-1)
# if stack is not empty
elif not stack.is_empty():
#then pop an element from stack if top of stack is smaller then arrayelement
while(not stack.is_empty() and arr[i] < stack.peek()):
stack.pop()
#while loop ends if one of 2 conditions true, if sack empty
#append -1 to result else append top of stack to result
if stack.is_empty():
result.append(-1)
else:
result.append(stack.peek())
# push the processesd element to stack
stack.push(arr[i])
result.reverse()
return result
arr = [11, 6, 42, 65, 32, 54]
print(nearest_smaller_to_right(arr))