Skip to content

Instantly share code, notes, and snippets.

@dashsaurabh
Last active January 4, 2020 10:33
Show Gist options
  • Save dashsaurabh/4d08507ae811c703d9a8de55588ab791 to your computer and use it in GitHub Desktop.
Save dashsaurabh/4d08507ae811c703d9a8de55588ab791 to your computer and use it in GitHub Desktop.
Min Value Stack Get in O(1)
class Node {
constructor(val){
this.val = val;
this.next = null;
}
}
class ItemStack {
constructor(){
this.first = null;
this.last = null;
this.length = 0;
this.minStack = new MinStack();
}
push(val){
let newNode = new Node(val)
if (this.length === 0){
this.first = newNode;
this.last = newNode;
}else{
let temp = this.first;
this.first = newNode;
this.first.next= temp;
}
this.minStack.push(val)
this.length++;
return this.length;
}
pop(){
if (this.length === 0) return null;
let temp = this.first;
if (this.length === 1){
this.last = null;
}
this.first = this.first.next;
this.length--;
if(temp.val === this.minStack.first.val){
this.minStack.pop()
}
return temp;
}
min(){
if(this.length === 0) return undefined;
else return this.minStack.first.val;
}
}
class MinStack {
constructor(){
this.first = null;
this.last = null;
this.length = 0;
}
push(val) {
let newNode = new Node(val);
if (this.length === 0) {
this.first = newNode;
this.last = newNode;
this.length++;
}else {
if (val < this.first.val) {
let temp = this.first;
this.first = newNode;
this.first.next= temp;
this.length++;
}
}
return this.length;
}
pop() {
let temp = this.first;
if (this.length === 1){
this.last = null;
}
this.first = this.first.next;
this.length--;
return temp;
}
}
let itemStack = new ItemStack();
itemStack.push(3);
itemStack.push(4);
itemStack.push(1);
console.log(itemStack.min());
itemStack.pop();
console.log(itemStack.min());
itemStack.pop();
console.log(itemStack.min());
itemStack.pop();
console.log(itemStack.min());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment