Simple cpp solution without any formulae


#1

stacks1;
stacks2;

MinStack::MinStack() {
while(s1.size())
s1.pop();

while(s2.size())
    s2.pop();

}

void MinStack::push(int x) {
s1.push(x);

if(s2.empty())
    s2.push(x);

else if(s1.top() < s2.top())
    s2.push(x);

}

void MinStack::pop() {
if(s1.empty())
return;

if(s1.top() == s2.top())
    s2.pop();
s1.pop();

}

int MinStack::top() {
if(s1.empty())
return -1;

return s1.top();

}

int MinStack::getMin() {
if(s1.empty())
return -1;
return s2.top();
}


#2

You have used stack to implement stack, that’s not the correct way to do it, use arrays or atlease vector , lol!


#3

No, that is how it is done. It’s a special stack with given conditions according to the question and stack STL is accepted.


#4

Can you please help me understand the problem statement? I don’t understand how will these functions work together as a single code?


#5

I dont understand your question. Whichever function is called will be executed, as in any program.


#6

What are you doing inside MinStack::MinStack() {}…
Why are you emptying the stacks?


#7

Read the question completely. They have said you can use extra stacks just empty them at the end.


#8

It specifically says not so to discuss Solution in problem section & you did just that.
Kindly refrain from doing so!!