Solution:
Extra Space:
Use two stack say stack1 and stack2. stack2 is used to keep track of Minimum number in the list at each step.
push( n ): stack1.push(n);
stack2.push( Min( n, stack2.top( ) ) );
pop( ): stack1.pop( );
stack2.pop( );
findMin( ): stack2.top( );
Extra Space:
Use two stack say stack1 and stack2. stack2 is used to keep track of Minimum number in the list at each step.
push( n ): stack1.push(n);
stack2.push( Min( n, stack2.top( ) ) );
pop( ): stack1.pop( );
stack2.pop( );
findMin( ): stack2.top( );
any way to optimize the second stack?
ReplyDeleteYes push value to second stack only if value <= min
ReplyDelete