Approach using stacks


#1

vector Solution::prevSmaller(vector &A) {
vectorG;
stackst;
for(int i=0;i<size(A);i++){
int flag=0;
if(st.empty()){
flag=1;
G.push_back(-1);
}
while(!st.empty()){
if(st.top()>=A[i]){ //we pop the stack till we get an element less than A[i]
st.pop();
}
else{
flag=1;
G.push_back(st.top());
//if we find some element less than A[i] then we push it into the result array.
break;
}
}
if(flag==0){
G.push_back(-1); //if no such element is found then push -1 into the result array.
}
st.push(A[i]);
}
return G;
}