Skip to content

Commit 115ecb3

Browse files
committedJan 30, 2025
Add solution #155
1 parent d40a93f commit 115ecb3

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,7 @@
149149
149|[Max Points on a Line](./0149-max-points-on-a-line.js)|Hard|
150150
151|[Reverse Words in a String](./0151-reverse-words-in-a-string.js)|Medium|
151151
152|[Maximum Product Subarray](./0152-maximum-product-subarray.js)|Medium|
152+
155|[Min Stack](./0155-min-stack.js)|Medium|
152153
160|[Intersection of Two Linked Lists](./0160-intersection-of-two-linked-lists.js)|Medium|
153154
162|[Find Peak Element](./0162-find-peak-element.js)|Medium|
154155
164|[Maximum Gap](./0164-maximum-gap.js)|Medium|

‎solutions/0155-min-stack.js

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/**
2+
* 155. Min Stack
3+
* https://leetcode.com/problems/min-stack/
4+
* Difficulty: Medium
5+
*
6+
* Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
7+
*
8+
* Implement the MinStack class:
9+
* - MinStack() initializes the stack object.
10+
* - void push(int val) pushes the element val onto the stack.
11+
* - void pop() removes the element on the top of the stack.
12+
* - int top() gets the top element of the stack.
13+
* - int getMin() retrieves the minimum element in the stack.
14+
*
15+
* You must implement a solution with O(1) time complexity for each function.
16+
*/
17+
18+
19+
var MinStack = function() {
20+
this.stack = [];
21+
};
22+
23+
/**
24+
* @param {number} val
25+
* @return {void}
26+
*/
27+
MinStack.prototype.push = function(val) {
28+
this.stack.push({ val, min: this.stack.length ? Math.min(val, this.getMin()) : val });
29+
};
30+
31+
/**
32+
* @return {void}
33+
*/
34+
MinStack.prototype.pop = function() {
35+
this.stack.pop();
36+
};
37+
38+
/**
39+
* @return {number}
40+
*/
41+
MinStack.prototype.top = function() {
42+
return this.stack[this.stack.length - 1].val;
43+
};
44+
45+
/**
46+
* @return {number}
47+
*/
48+
MinStack.prototype.getMin = function() {
49+
return this.stack.length ? this.stack[this.stack.length - 1].min : 0;
50+
};

0 commit comments

Comments
 (0)
Please sign in to comment.