MrainW's Home

All things come to those who wait!

0%

LeetCode 155. Min Stack

Question

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.

https://leetcode.com/problems/min-stack/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class MinStack {
//two stack
Stack<int[]> stack = new Stack<>();
public void push(int x) {
if(stack.isEmpty()){
stack.push(new int[]{x,x});
return;
}
int min = stack.peek()[1];
stack.push(new int[]{x,Math.min(x,min)});
}
public void pop(){
stack.pop();
}

public int top(){
return stack.peek()[0];
}

public int getMin(){
return stack.peek()[1];
}
}

Complexity:

Time complexity: O(1)

Space complexity: O(1)

Welcome to my other publishing channels