LeetCode: Maximum Frequency Stack Solution

1var FreqStack = function () {
2 this.freqMap = new Map()
3 this.freqWithElsArr = []
4 this.mostFreq = 0
5}
6
7/**
8 * @param {number} x
9 * @return {void}
10 */
11FreqStack.prototype.push = function (x) {
12 const freq = (this.freqMap.get(x) || 0) + 1
13 if (!this.freqWithElsArr[freq]) {
14 this.freqWithElsArr[freq] = []
15 }
16
17 this.freqWithElsArr[freq].push(x)
18 this.freqMap.set(x, freq)
19 this.mostFreq = Math.max(this.mostFreq, freq)
20
21 return null
22}
23
24/**
25 * @return {number}
26 */
27FreqStack.prototype.pop = function () {
28 const x = this.freqWithElsArr[this.mostFreq].pop()
29
30 if (this.freqWithElsArr[this.mostFreq].length === 0) {
31 this.mostFreq--
32 }
33
34 this.freqMap.set(x, this.freqMap.get(x) - 1)
35
36 return x
37}
38
39/**
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

HoningJS

Search Posts