Skip to content

Commit

Permalink
Day 8 :: Minimum Stack
Browse files Browse the repository at this point in the history
  • Loading branch information
vitalish committed Oct 15, 2024
1 parent f422d43 commit 0224703
Show file tree
Hide file tree
Showing 3 changed files with 112 additions and 0 deletions.
44 changes: 44 additions & 0 deletions src/main/java/com/vitalish/leetcode/stack/MinStack.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package com.vitalish.leetcode.stack;

/**
* Minimum Stack
*
* @see https://neetcode.io/problems/minimum-stack
*/
public class MinStack {

private Node<Integer> top;
private Node<Integer> 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>(
Integer value,
Node<Integer> next
) {
private Node(Integer value) {
this(value, null);
}
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package com.vitalish.leetcode.stack;

import java.util.Stack;

public class MinStackWithInternalStack {

private Stack<Integer> top;
private Stack<Integer> 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();
}

}
35 changes: 35 additions & 0 deletions src/test/java/com/vitalish/leetcode/stack/MinStackTest.java
Original file line number Diff line number Diff line change
@@ -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
}
}

0 comments on commit 0224703

Please sign in to comment.