I am solving interview question from here.
Problem : Given an array, find the nearest smaller element G[i] for every element A[i] in the array such that the element has an index smaller than i.
More formally,
G[i]
for an elementA[i]
= an elementA[j]
such thatj is maximum possible
andj < i
andA[j] < A[i]
. Elements for which no smaller element exist, consider next smaller element as-1
.Example: Input :
A : [4, 5, 2, 10, 8]
Return :[-1, 4, -1, 2, 2]
How can I optimise my solution:
def prev_smaller(arr):
new_stack = []
status = False
for i in range(len(arr)):
for j in range(i,-1,-1):
if arr[i]>arr[j]:
status = True
new_stack.append(arr[j])
break
if not status:
new_stack.append(-1)
status = False
return new_stack
assert prev_smaller([34,35,27,42,5,28,39,20,28]) == [-1,34,-1,27,-1,5,28,5,20]
assert prev_smaller([1]) == [-1]
assert prev_smaller([1,4,5,6]) ==[-1,1,4,5]