Skip to content

Instantly share code, notes, and snippets.

@vitkarpov
Last active March 5, 2017 13:21
Show Gist options
  • Save vitkarpov/edef7ad127e3224c146f26d1cfb86ff3 to your computer and use it in GitHub Desktop.
Save vitkarpov/edef7ad127e3224c146f26d1cfb86ff3 to your computer and use it in GitHub Desktop.
"Cracking the coding interview", Stacks and Queues, 3.2
/**
* Стек, который реализует метод min,
* кроме стандартный push и pop
*
* @example
* const s = new Stack();
* s.push(5);
* // 5
* console.log(s.min());
* s.push(6);
* s.push(3);
* // 3
* console.log(s.min());
* s.push(7);
* s.pop();
* s.pop();
* // 5
* console.log(s.min());
*/
class Stack {
constructor() {
this._s1 = [];
this._s2 = [];
}
push(value) {
if (value <= this.min()) {
this._s2.push(value);
}
this._s1.push(value);
}
pop() {
const value = this._s1.pop();
if (value === this.min()) {
this._s2.pop();
}
return value;
}
min() {
if (this._s2.length === 0) {
return Number.MAX_SAFE_INTEGER;
}
return this._s2[this._s2.length - 1];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment