LeetCode: Maximum Frequency Stack Solution
1var FreqStack = function () {2 this.freqMap = new Map()3 this.freqWithElsArr = []4 this.mostFreq = 05}67/**8 * @param {number} x9 * @return {void}10 */11FreqStack.prototype.push = function (x) {12 const freq = (this.freqMap.get(x) || 0) + 113 if (!this.freqWithElsArr[freq]) {14 this.freqWithElsArr[freq] = []15 }1617 this.freqWithElsArr[freq].push(x)18 this.freqMap.set(x, freq)19 this.mostFreq = Math.max(this.mostFreq, freq)2021 return null22}2324/**25 * @return {number}26 */27FreqStack.prototype.pop = function () {28 const x = this.freqWithElsArr[this.mostFreq].pop()2930 if (this.freqWithElsArr[this.mostFreq].length === 0) {31 this.mostFreq--32 }3334 this.freqMap.set(x, this.freqMap.get(x) - 1)3536 return x37}3839/**40 * Your FreqStack object will be instantiated and called as such:41 * var obj = new FreqStack()42 * obj.push(x)43 * var param_2 = obj.pop()44 */
Comments
Loading comments...
Tags
leetcode
hash table
stack
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: Set Mismatch
Mar 2, 2021
Previous Post
LeetCode: Count Items Matching A Rule
Feb 28, 2021