Thursday, March 7, 2013

[Cracking the Code Interview 4th Edition] 3.2

How would you design a stack which, in addition to push and pop, also has a function min which returns the minimum element? 
Push, pop and min should all operate in O(1) time.

Thought:

1. We could modify the Node class in this stack. We add a local min variable in every Node which stores the local min of all the nodes under & including this one in the stack. 
Thus when pushing, we update the stack, and the top node's min.
When pop, just pop. Min is just peeking the min variable of the top Node.

2. We could change our mind to using another stack who stores the local min.
When pushing, we push the new local min value if and only if the pushed Node's value is smaller or equal to the current local min. That is, if our local min is 3 and we want to push a Node with value 4, the local min stack will not be updated.
When popping, if the popped value is equal to the local min, then pop them respectively.

The first method use extra space within every Node.
The second method use extra space of a stack.

No comments:

Post a Comment