Skip to content

Instantly share code, notes, and snippets.

@primaryobjects
Created October 14, 2023 15:40
Show Gist options
  • Select an option

  • Save primaryobjects/fd89a686f94aeaba1654ea3d8ec6c4bc to your computer and use it in GitHub Desktop.

Select an option

Save primaryobjects/fd89a686f94aeaba1654ea3d8ec6c4bc to your computer and use it in GitHub Desktop.
public class MinStack {
private struct Item
{
public int Val;
public int ParentMin;
};
private int _min;
private List<Item> _stack;
private int _minIndex;
public MinStack() {
_stack = new List<Item>();
_minIndex = 0;
}
public void Push(int val) {
_stack.Add(new Item() { Val = val, ParentMin = _minIndex });
if (val < _stack[_minIndex].Val)
{
_minIndex = _stack.Count - 1;
}
}
public void Pop() {
_minIndex = _stack[_stack.Count - 1].ParentMin;
_stack.RemoveAt(_stack.Count - 1);
}
public int Top() {
return _stack[_stack.Count - 1].Val;
}
public int GetMin() {
return _stack[_minIndex].Val;
}
}
/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.Push(val);
* obj.Pop();
* int param_3 = obj.Top();
* int param_4 = obj.GetMin();
*/
155. Min Stack
Solved
Medium
Topics
Companies
Hint
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
Implement the MinStack class:
MinStack() initializes the stack object.
void push(int val) pushes the element val onto the stack.
void pop() removes the element on the top of the stack.
int top() gets the top element of the stack.
int getMin() retrieves the minimum element in the stack.
You must implement a solution with O(1) time complexity for each function.
Example 1:
Input
["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]
Output
[null,null,null,null,-3,null,0,-2]
Explanation
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); // return -3
minStack.pop();
minStack.top(); // return 0
minStack.getMin(); // return -2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment