We can think of two different solutions -
Sol 1:
With additional memory where time complexity of findmin(),Push(),Pop() is O(1) but space complexity is O(n). Along with pushing the elements push the current minimum on to the stack. For pop operation pop 2 elements instead of 1 , it is still O(1).
For ex: Let us assume the following numbers which are pushed on to the stack.
4 2 9 3 6 1
Stack state will be something like below
4 4 2 2 9 2 3 2 6 2 1 1.
POP(x) = pop(), pop().
Where POP(x) is modified stack pop operation. pop() is standard pop() operation.
FINDMIN(x)=pop()
PUSH(x)=push() and push( MIN(pop(),elem)).
Where PUSH(x) is modified stack push operation. push() is standard push() operation.
Here storage needed for stack is 2n where n is number of elements in the stack.
There is another optimal solution which i will post later.
Categories
FollowersBlog Archive
Jobs
Find more freelance jobs
|
Sunday, February 17, 2008
Subscribe to:
Posts (Atom)
|
Popular Posts
|