LeetCode: Min Stack Solution
Linked list in actionApproach
Use an linked list to store stack
Head node will be top of the stack and will store the minimum of the stack
Every push will recalculate the minimum
Implementation
1function Node(val, min, next) {2 this.val = val3 this.min = min4 this.next = next5}67var MinStack = function () {8 this.head = null9}1011MinStack.prototype.push = function (val) {12 this.head = new Node(13 val,14 this.head ? Math.min(val, this.head.min) : val,15 this.head16 )17}1819MinStack.prototype.pop = function () {20 this.head = this.head.next21}2223MinStack.prototype.top = function () {24 return this.head.val25}2627MinStack.prototype.getMin = function () {28 return this.head.min29}
References
Similar problems
Sliding Window Maximum
Max Stack
Comments
Loading comments...
Tags
leetcode
stack
linked list
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.
Next Post
LeetCode: Nearest Exit from Entrance in Maze
BFS with a notice
Previous Post
LeetCode: Make The String Great
Keep removing until all is good