Golgappa.net | Golgappa.org | BagIndia.net | BodyIndia.Com | CabIndia.net | CarsBikes.net | CarsBikes.org | CashIndia.net | ConsumerIndia.net | CookingIndia.net | DataIndia.net | DealIndia.net | EmailIndia.net | FirstTablet.com | FirstTourist.com | ForsaleIndia.net | IndiaBody.Com | IndiaCab.net | IndiaCash.net | IndiaModel.net | KidForum.net | OfficeIndia.net | PaysIndia.com | RestaurantIndia.net | RestaurantsIndia.net | SaleForum.net | SellForum.net | SoldIndia.com | StarIndia.net | TomatoCab.com | TomatoCabs.com | TownIndia.com
Interested to Buy Any Domain ? << Click Here >> for more details...


Implement a stack with push (), pop() and min() in O(1) time.



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

Post New Answer

More Core Java Interview Questions

What is quick sort in java?

1 Answers  


What is java jit compilers?

1 Answers  


Can we have any code between try and finally blocks?

1 Answers  


Is binary a low level language?

1 Answers  


What is gui programming?

1 Answers  


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?

1 Answers  


What is JFC?

1 Answers  


What is java used for on a computer?

1 Answers  


What is math exp in java?

1 Answers  


What is Runtime class and its purpose?

2 Answers  


Categories