Implement a stack with push (), pop() and min() in O(1) time.
Answer Posted / 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 |
Post New Answer View All Answers
What is java string pool?
Is minecraft 1.15 out?
How to create a base64 decoder in java8?
What is the difference between break and continue statements?
Realized?
Differentiate between static and non-static methods in java.
How to sort array in descending order in java?
Write a program to print count of empty strings in java 8?
explain different ways of using thread? : Java thread
Write a java program to find the route that connects between Red and Green Cells. General Rules for traversal 1. You can traverse from one cell to another vertically, horizontally or diagonally. 2. You cannot traverse through Black cells. 3. There should be only one Red and Green cell and at least one of each should be present. Otherwise the array is invalid. 4. You cannot revisit a cell that you have already traversed. 5. The maze need not be in the same as given in the above example
What is parsing in java?
Write a program to find the whether a number is an Armstrong number or not?
Explain public static void main(string args[]) in java.
What is a constructor overloading in java?
What are the differences between heap and stack memory in java?