diff --git a/src/main/java/com/vitalish/leetcode/stack/MinStack.java b/src/main/java/com/vitalish/leetcode/stack/MinStack.java new file mode 100644 index 0000000..4dfc839 --- /dev/null +++ b/src/main/java/com/vitalish/leetcode/stack/MinStack.java @@ -0,0 +1,44 @@ +package com.vitalish.leetcode.stack; + +/** + * Minimum Stack + * + * @see https://neetcode.io/problems/minimum-stack + */ +public class MinStack { + + private Node top; + private Node min; + + public MinStack() { + + } + + public void push(int val) { + min = new Node<>(Math.min(val, min != null ? min.value : val), min); + top = new Node<>(val, top); + } + + public void pop() { + min = min.next; + top = top.next; + } + + public int top() { + return top.value; + } + + public int getMin() { + return min.value; + } + + private record Node( + Integer value, + Node next + ) { + private Node(Integer value) { + this(value, null); + } + } + +} diff --git a/src/main/java/com/vitalish/leetcode/stack/MinStackWithInternalStack.java b/src/main/java/com/vitalish/leetcode/stack/MinStackWithInternalStack.java new file mode 100644 index 0000000..17a8ff2 --- /dev/null +++ b/src/main/java/com/vitalish/leetcode/stack/MinStackWithInternalStack.java @@ -0,0 +1,33 @@ +package com.vitalish.leetcode.stack; + +import java.util.Stack; + +public class MinStackWithInternalStack { + + private Stack top; + private Stack min; + + public MinStackWithInternalStack() { + top = new Stack<>(); + min = new Stack<>(); + } + + public void push(int val) { + top.push(val); + min.push(Math.min(min.isEmpty() ? val : min.peek(), val)); + } + + public void pop() { + top.pop(); + min.pop(); + } + + public int top() { + return top.peek(); + } + + public int getMin() { + return min.peek(); + } + +} diff --git a/src/test/java/com/vitalish/leetcode/stack/MinStackTest.java b/src/test/java/com/vitalish/leetcode/stack/MinStackTest.java new file mode 100644 index 0000000..6781ddc --- /dev/null +++ b/src/test/java/com/vitalish/leetcode/stack/MinStackTest.java @@ -0,0 +1,35 @@ +package com.vitalish.leetcode.stack; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +class MinStackTest { + + @Test + void checksMinStack() { + MinStack minStack = new MinStack(); + minStack.push(1); + minStack.push(2); + minStack.push(0); + + Assertions.assertEquals(0, minStack.getMin()); // return 0 + + minStack.pop(); + Assertions.assertEquals(2, minStack.top()); // return 2 + Assertions.assertEquals(1, minStack.getMin()); // return 1 + } + + @Test + void checksMinStackWithInternalStack() { + MinStackWithInternalStack minStack = new MinStackWithInternalStack(); + minStack.push(1); + minStack.push(2); + minStack.push(0); + + Assertions.assertEquals(0, minStack.getMin()); // return 0 + + minStack.pop(); + Assertions.assertEquals(2, minStack.top()); // return 2 + Assertions.assertEquals(1, minStack.getMin()); // return 1 + } +} \ No newline at end of file