educative.io

Educative

MaxStack: Implementation does not match description

See my comments inline:

//removes and returns value from stack
public int pop(){
// From Description: The `pop()` function pops off from the `mainStack` as usual. 
// However, it only pops off the `maxStack` if the value popped from the `mainStack`
// is equal to the top of the `maxStack`.
//
// I do not see above functionality here. It will always remove from maxStack.
    maxStack.pop();
    return mainStack.pop();
}
//pushes value into the stack
public void push(Integer value){
    mainStack.push(value);
    if(!maxStack.isEmpty() && maxStack.top() > value)
// This doesn't match description. Here we push duplicates of max value into maxStack which is not explained.
        maxStack.push(maxStack.top());
    else
        maxStack.push(value);
}

Type your question above this line.

Course: https://www.educative.io/collection/10370001/4938268330688512
Lesson: https://www.educative.io/collection/page/10370001/4938268330688512/6384629655797760

Dear @Roman_Urosov,

  • pop() function always pops off the mainStack value but does not always pops off the maxStack. It will only pop off the maxStack when the value which needs to be popped off from mainStack is equal to the top of maxStack.
  • There is a difference in maxStack and mainStack.
  • push() function always pushes in the value. The given condition if(!maxStack.isEmpty() && maxStack.top() > value) states that when the maxStack would not be empty and when the top of the maxStack is greater than the value which is going to be pushed in. If both satisfy, it will be pushed; otherwise, it won’t.
  • push() function above will only happen if they satisfy the given two conditions in the if statement.

Hope it helps!