Min Stack Problem
Problem Statement
Design a min stack that allows the following operations:
- : Pushes element
push(int x)onto the stack.x - : Removes and returns the top element from the stack. If the stack is empty, it returns
pop().-1 - : Returns the top element from the stack without removing it.
top() - : Returns the minimum element in the stack.
getMin()
Rules and Constraints
- The and
pushoperations should take constant time.pop - The and
topoperations should take constant time.getMin - The total memory used should be O(n) where n is the number of elements pushed into the stack.
Notes
The min stack should handle the following edge cases:
- When the stack is empty, should return
pop().-1 - When no elements are pushed into the stack, should return a meaningful value (i.e. not a default value or error).
getMin() - When the only element pushed into the stack is popped out, the operation should return the same result as when the element was first pushed into the stack.
getMin()
The min stack should maintain the order in which elements were pushed onto the stack.
Example
Input: {"operations":["push","push","getMin"]} Output: [null,null,-3]
CompaniesGoogle
JavaScript
Login to write code
Solve problems, verify your skills, and earn XP.