[InterviewBit] Min Stack

Min Stack

  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
vector<int> st;
vector<int> mi;
MinStack::MinStack() {
st.clear();
mi.clear();
}

void MinStack::push(int x) {
st.push_back(x);
if(mi.empty()) mi.push_back(st.size() - 1);
else {
if(st[mi.back()] > st.back()) mi.push_back(st.size() - 1);
}
}

void MinStack::pop() {
if(st.empty()) return;
st.pop_back();
if(st.size() == mi.back()) mi.pop_back();
}

int MinStack::top() {
if(st.empty()) return -1;
return st.back();
}

int MinStack::getMin() {
if(mi.empty()) return -1;
return st[mi.back()];
}


Author: Song Hayoung
Link: https://songhayoung.github.io/2022/09/16/PS/interviewbit/min-stack/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.