Given an array A[1..n]
, we want to compute another array B[1..n]
such that B[i]
stores the nearest element to the left of A[i]>
B[1]=A[1]
push(B[1])
for i=2 to n do
{
while(A[i] > stack_top ANS stack_top!=NULL)
pop()
if(stack_top=NULL)
B[i]=A[i]
else
B[i]=stack_top
push(A[i])
}
As IVlad pointed out that each element is pushed and poped atmost once, time is O(n).
pl do correct me if there is some mistake, and I am curious for any alternate solution which avoids stack and is cheaper.