Saturday, 5 March 2016

Stack | Get Minimum or Maximum Element in O(1) from Stack

The easiest way to achieve this is to create an auxiliary stack and keep pushing minimum ( maximum ) element in it . And to maintain consistency while popping , pop from when auxiliary stack when top elements in both stacks are equal.


Pseudocode :

Stack myStack = new Stack();
Stack maxStack = new Stack ();

void push(int data )
{
    if ( maxStack.isEmpty() || maxStack.peek() < data)
                  maxStack().push(data);

   myStack.push(data);

}

int pop ()
{
          int num = myStack.pop();
        if( ! maxStack.isEmpty() && maxStack.peek() == num )
                      return maxStack.pop();
        return num;
}

No comments:

Post a Comment