File tree Expand file tree Collapse file tree 1 file changed +56
-0
lines changed Expand file tree Collapse file tree 1 file changed +56
-0
lines changed Original file line number Diff line number Diff line change
1
+ //////////////////////////////////////////////////////////////////////////////
2
+ // Two Stacks
3
+ // Time: O(1)
4
+ // Space: O(n)
5
+ // This solution uses two stacks to save the total values and the minimum
6
+ // values. Per each new value if it is less than or equal to the current
7
+ // minimum it is pushed to both stacks. We save duplicate minimum values to
8
+ // avoid the conundrum of inquiring whether the minimum value can be removed
9
+ // (i.e. when the minimum value equals the top value can it be removed or are
10
+ // there duplicate values in the main stack).
11
+ //////////////////////////////////////////////////////////////////////////////
12
+
13
+ class MinStack {
14
+ /**
15
+ * @constructor
16
+ */
17
+ constructor ( ) {
18
+ this . mainStack = [ ] ;
19
+ this . minStack = [ ] ;
20
+ }
21
+
22
+ /**
23
+ * @param {number } val
24
+ * @return {void }
25
+ */
26
+ push ( val ) {
27
+ this . mainStack . push ( val ) ;
28
+ if ( ! this . minStack . length || val <= this . minStack [ this . minStack . length - 1 ] ) {
29
+ this . minStack . push ( val ) ;
30
+ }
31
+ }
32
+
33
+ /**
34
+ * @return {void }
35
+ */
36
+ pop ( ) {
37
+ const val = this . mainStack . pop ( ) ;
38
+ if ( val === this . minStack [ this . minStack . length - 1 ] ) {
39
+ this . minStack . pop ( ) ;
40
+ }
41
+ }
42
+
43
+ /**
44
+ * @return {number }
45
+ */
46
+ top ( ) {
47
+ return this . mainStack [ this . mainStack . length - 1 ] ;
48
+ }
49
+
50
+ /**
51
+ * @return {number }
52
+ */
53
+ getMin ( ) {
54
+ return this . minStack [ this . minStack . length - 1 ] ;
55
+ }
56
+ }
You can’t perform that action at this time.
0 commit comments