MCPcopy Create free account
hub / github.com/careercup/CtCI-6th-Edition-JavaScript / StackMin

Class StackMin

chapter03/3.2 - Stack Min/stackMin.js:5–33  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

3// Approach, keep an additional stack that keeps the mins
4
5class StackMin extends Stack {
6 constructor() {
7 super();
8 // additional stack to track the mins
9 this._minStack = new Stack();
10 this._min = null;
11 }
12
13 push(value) {
14 super.push(value);
15 if (this._min == null || value <= this._min) {
16 this._min = value;
17 this._minStack.push(value);
18 }
19 }
20
21 pop() {
22 let value = super.pop();
23 if (value == this._minStack.peek()) {
24 this._minStack.pop();
25 this._min = this._minStack.peek();
26 }
27 return value;
28 }
29
30 min() {
31 return this._min;
32 }
33}
34
35/* TEST */
36

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected