Interview question: Design a data structure which has the following features
- push the data
- pops the last inserted data [LIFO]
- Gives the minimum
All of the above operations should have a complexity of O(1)
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You can do this by maintaining two stacks
stack– do the usual push and pop operations on this stack.minStack– this stack is used to get the min ele in the stack inO(1)time. At any point the top element of this stack will be the min of all the elements in the stack.In the above solution every time an element is pushed on stack, there is a corresponding push on
minStack. So at any time the number of elements in stack andminStackare same. We can slightly optimize it by pushing an element ontominStackonly if the element is smaller then the present min.