Implement a stack with push (), pop() and min() in O(1) time.
Answer / Makeshwar Tanti
To implement a stack with `push`, `pop`, and `min` operations in O(1) average time, you can use a combination of LinkedList for the data structure and TreeSet to store the minimum element. Here's an implementation:n```nclass MinStack {n private final Stack<Integer> data = new Stack<>();n private final TreeSet<Integer> min = new TreeSet<>();n public void push(int val) {n data.push(val);n if (min.isEmpty() || min.last() > val) {n min.add(val);n }n min.add(min.tailSet(val).last());n }n public int pop() {n int top = data.pop();n min.remove(top);n return top;n }n public int min() {n return min.first();n }n}n```
| Is This Answer Correct ? | 0 Yes | 0 No |
What is quick sort in java?
What is java jit compilers?
Can we have any code between try and finally blocks?
Is binary a low level language?
What is gui programming?
What is constructor
9 Answers Manforce, Tech Mahindra,
What is static variable and static method?
32 Answers Accenture, Prolific, Prolifics, TCS, TNH,
What is an example of a keyword?
What is JFC?
What is java used for on a computer?
What is math exp in java?
What is Runtime class and its purpose?