File tree 1 file changed +63
-0
lines changed
src/main/java/com/ctci/stacksandqueues
1 file changed +63
-0
lines changed Original file line number Diff line number Diff line change
1
+ package com .ctci .stacksandqueues ;
2
+
3
+ import com .sun .tools .javac .util .Assert ;
4
+
5
+ import java .util .Stack ;
6
+
7
+ /**
8
+ * How would you design a stack which, in addition to push and pop, has a function min
9
+ * which returns the minimum element? Push, pop and min should all operate in 0(1) time.
10
+ *
11
+ * @author rampatra
12
+ * @since 2019-02-04
13
+ */
14
+ public class StackMin {
15
+
16
+ // the main stack to do push, pop, and min operations
17
+ private static Stack <Integer > stack = new Stack <>();
18
+ // another stack to store the mins (needed to make min() call O(1))
19
+ private static Stack <Integer > minStack = new Stack <>();
20
+
21
+ private static int push (int item ) {
22
+ minPush (item );
23
+ return stack .push (item );
24
+ }
25
+
26
+ private static int pop () {
27
+ minPop (stack .peek ());
28
+ return stack .pop ();
29
+ }
30
+
31
+ private static int min () {
32
+ return minStack .peek ();
33
+ }
34
+
35
+ private static void minPush (int item ) {
36
+ if (minStack .empty () || item <= minStack .peek ()) {
37
+ minStack .push (item );
38
+ }
39
+ }
40
+
41
+ private static void minPop (int item ) {
42
+ if (item == minStack .peek ()) {
43
+ minStack .pop ();
44
+ }
45
+ }
46
+
47
+ public static void main (String [] args ) {
48
+ push (2 );
49
+ push (5 );
50
+ push (1 );
51
+ push (1 );
52
+ push (6 );
53
+ push (8 );
54
+ Assert .check (min () == 1 );
55
+ pop ();
56
+ pop ();
57
+ pop ();
58
+ Assert .check (min () == 1 );
59
+ pop ();
60
+ Assert .check (min () == 2 );
61
+
62
+ }
63
+ }
You can’t perform that action at this time.
0 commit comments