Skip to content

Commit 81b693a

Browse files
1st solution for Min Max Stack Construction
1 parent a08ed40 commit 81b693a

File tree

2 files changed

+122
-0
lines changed

2 files changed

+122
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
// Feel free to add new properties and methods to the class.
2+
class MinMaxStack {
3+
constructor() {
4+
this.stack = [];
5+
this.minValue = null;
6+
this.maxValue = null;
7+
}
8+
9+
getStack() {
10+
return this.stack;
11+
}
12+
13+
peek() {
14+
return this.stack[this.stack.length - 1];
15+
}
16+
17+
pop() {
18+
this.minValue = null;
19+
this.maxValue = null;
20+
21+
const length = this.stack.length - 1;
22+
const poped = this.stack[length];
23+
let oldStack = this.stack;
24+
let start = 0;
25+
let end = length - 1;
26+
27+
this.stack = [];
28+
29+
if (start === end) {
30+
this.push(oldStack[start]);
31+
}
32+
33+
while (start < end) {
34+
this.push(oldStack[start]);
35+
this.push(oldStack[end]);
36+
37+
start += 1;
38+
end -= 1;
39+
}
40+
41+
return poped;
42+
}
43+
44+
push(number) {
45+
this.minValue = null;
46+
this.maxValue = null;
47+
48+
this.stack[this.stack.length] = number;
49+
}
50+
51+
getMin() {
52+
if (this.minValue) return this.minValue;
53+
54+
let min = this.stack[0];
55+
let start = 1;
56+
let end = this.stack.length;
57+
58+
while (start <= end) {
59+
if (this.stack[start] < min) {
60+
min = this.stack[start];
61+
}
62+
63+
if (this.stack[end] < min) {
64+
min = this.stack[end];
65+
}
66+
67+
start += 1;
68+
end -= 1;
69+
}
70+
71+
this.minValue = min;
72+
73+
return this.minValue;
74+
}
75+
76+
getMax() {
77+
if (this.maxValue) return this.maxValue;
78+
79+
let max = this.stack[0];
80+
let start = 1;
81+
let end = this.stack.length;
82+
83+
while (start <= end) {
84+
if (this.stack[start] > max) {
85+
max = this.stack[start];
86+
}
87+
88+
if (this.stack[end] > max) {
89+
max = this.stack[end];
90+
}
91+
92+
start += 1;
93+
end -= 1;
94+
}
95+
96+
this.maxValue = max;
97+
98+
return this.maxValue;
99+
}
100+
}
101+
102+
exports.MinMaxStack = MinMaxStack;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import { MinMaxStack } from "./min-max-stack-construction";
2+
3+
function testMinMaxPeek(min, max, peek, stack) {
4+
expect(stack.getMin()).toEqual(min);
5+
expect(stack.getMax()).toEqual(max);
6+
expect(stack.peek()).toEqual(peek);
7+
}
8+
9+
it("Test Case #1", function () {
10+
const stack = new MinMaxStack();
11+
stack.push(5);
12+
testMinMaxPeek(5, 5, 5, stack);
13+
stack.push(7);
14+
testMinMaxPeek(5, 7, 7, stack);
15+
stack.push(2);
16+
testMinMaxPeek(2, 7, 2, stack);
17+
expect(stack.pop()).toEqual(2);
18+
expect(stack.pop()).toEqual(7);
19+
testMinMaxPeek(5, 5, 5, stack);
20+
});

0 commit comments

Comments
 (0)