-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathProblem_02.java
120 lines (108 loc) · 2.61 KB
/
Problem_02.java
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
/**
* Cracking-The-Coding-Interview
* Problem_02.java
*/
package com.deepak.ctci.Ch03_Stacks_And_Queues;
import java.util.NoSuchElementException;
import java.util.Stack;
/**
* <br> Problem Statement :
*
* How would you design a stack which, in addition to push and pop,
* has a function min() which returns a minimum element? Push, pop
* and min, all should operate in O(1) time
*
* </br>
*
* @author Deepak
*/
public class Problem_02 {
/**
* Custom stack implemented
*
* @author Deepak
*/
public static class CustomStack {
/* Array to keep track of main stack */
private Integer[] array;
/* Size of main stack */
private int size = 0;
/* Creating a new stack for min value since we want O(1) solution
* and looping through array to find min is not O(1) */
private Stack<Integer> stackForMinValue = new Stack<>();
/**
* Constructor
*
* @param capacity
*/
public CustomStack(int capacity) {
array = new Integer[capacity];
}
/**
* Method to push an item in the stack
*
* @param item
*/
public void push(Integer item) {
/* If length of array has reached size, array is full */
if (size == array.length) {
throw new IllegalStateException("Cannot insert on full stack");
}
/* Push item to stack for min value */
pushToStackForMinValue(item);
/* insert in array at last */
array[size++] = item;
}
/**
* Method to push minimum value to stack
*
* @param item
*/
private void pushToStackForMinValue(Integer item) {
/* Check if stack is empty (We will hold just one min value here).
* If it is empty, simply push the item, else compare with the existing
* one, if it is smaller, pop the one available in stack and push this new
* smaller one. */
if (!stackForMinValue.isEmpty()) {
if (item < stackForMinValue.peek()) {
stackForMinValue.pop();
stackForMinValue.push(item);
}
} else {
stackForMinValue.push(item);
}
}
/**
* Method to pop the element from the stack
*
* @return {@link Integer}
*/
public Integer pop() {
/* If size is zero, cannot pop */
if (size == 0) {
throw new NoSuchElementException("Cannot pop from empty stack");
}
/* Find the element to be returned and adjust array */
Integer result = array[size - 1];
array[size - 1] = null;
size--;
return result;
}
/**
* Method to get size of the stack
*
* @return {@link}
*/
public int size() {
return size;
}
/**
* Method to find minimum value
*
* @return {@link Integer}
*/
public Integer min() {
return stackForMinValue.peek();
}
}
}