LET'S TALK TECHNICAL

This blog is intended to help people prepare for the job interviews and improve their analytical skills. We have posted difficult datastructures and algorithm questions and puzzles. Interview experiences section is for the people to post their interview experiences.Views expressed here are of their personal and the blog author doesn't take any responsibility for the same.

-

Followers

Jobs

Sunday, February 17, 2008

Design a stack which have O(1) time complexity for finding the minimum element?

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.

Popular Posts