Can anyone help me with Nearest Smaller Element problem using stack?

void solve(vector A)

{

stack g;

vector R;

g.push(-1);

for(int x: A){

if(x > g.top()){

  R.push_back(g.top());

}

else{

  while(g.top() >= x){

    g.pop();

  }

  R.push_back(-1);

}

g.push(x);

}

for(int i=0; i<R.size(); ++i){

cout<<R[i]<<" ";

}

R.clear();

cout<<"\n";

}

Input:
8
39 27 11 4 24 32 32 1

My Output:
-1 -1 -1 -1 4 24 -1 -1

Correct Output:
-1 -1 -1 -1 4 24 24 -1

Point 1: Please post link to the problem.

Point 2: Format your code or post a link to the code with better readability.

As far as I remember, this is Hackerearth’s problem or something similar.

I guess the mistake in your code is at line:
R.push_back(-1)
it should be R.push_back(st.top()) since you already have -1 in the stack.

You can als o choose to debug your code and find it out yourself by printing stack.top and R.back() at every step. Enjoy!

Edit: A few tips to get faster response to your problem

1 Like

You got it right.
Thanks!

1 Like