Post

Min Stack

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

push(x) – Push element x onto stack.
pop() – Removes the element on top of the stack.
top() – Get the top element.
getMin() – Retrieve the minimum element in the stack.

Constraints: Methods pop, top and getMin operations will always be called on non-empty stacks.

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class MinStack {

    List<Integer> stack;

    public MinStack() {
      stack = new ArrayList<>();
    }

    public void push(int x) {
      stack.add(x);
    }

    public void pop() {
      stack.remove(stack.size() - 1);
    }

    public int top() {
      return stack.get(stack.size() - 1);
    }

    public int getMin() {
      return Collections.min(stack);
    }
}

Source: leetcode

This post is licensed under CC BY 4.0 by the author.