Skip to content

Commit

Permalink
Merge pull request neetcode-gh#1926 from AkifhanIlgaz/0895
Browse files Browse the repository at this point in the history
Create: 0895-maximum-frequency-stack.rs / .ts / .js
  • Loading branch information
tahsintunan authored Jan 7, 2023
2 parents 66ff35f + 2383343 commit 686c2e9
Show file tree
Hide file tree
Showing 3 changed files with 96 additions and 0 deletions.
29 changes: 29 additions & 0 deletions javascript/0895-maximum-frequency-stack.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
class FreqStack {
constructor() {
this.cnt = {};
this.maxCnt = 0;
this.stacks = {};
}

push(val) {
let valCnt = 1 + (this.cnt[val] || 0);
this.cnt[val] = valCnt;

if (valCnt > this.maxCnt) {
this.maxCnt = valCnt;
this.stacks[valCnt] = [];
}
this.stacks[valCnt].push(val);
}

pop() {
let res = this.stacks[this.maxCnt].pop();
this.cnt[res] -= 1;

if (this.stacks[this.maxCnt].length == 0) {
this.maxCnt -= 1;
}

return res;
}
}
35 changes: 35 additions & 0 deletions rust/0895-maximum-frequency-stack.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
use std::collections::HashMap;
struct FreqStack {
count: HashMap<i32, i32>,
max_count: i32,
stacks: HashMap<i32, Vec<i32>>,
}

impl FreqStack {
fn new() -> Self {
Self {
count: HashMap::new(),
max_count: 0,
stacks: HashMap::new(),
}
}

fn push(&mut self, val: i32) {
let val_count = 1 + *self.count.get(&val).or(Some(&0)).unwrap();
self.count.insert(val, val_count);
if val_count > self.max_count {
self.max_count = val_count;
self.stacks.insert(val_count, vec![]);
}
self.stacks.get_mut(&val_count).unwrap().push(val);
}

fn pop(&mut self) -> i32 {
let res = self.stacks.get_mut(&self.max_count).unwrap().pop().unwrap();
*self.count.get_mut(&res).unwrap() -= 1;
if self.stacks.get(&self.max_count).unwrap().is_empty() {
self.max_count -= 1;
}
res
}
}
32 changes: 32 additions & 0 deletions typescript/0895-maximum-frequency-stack.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
class FreqStack {
cnt: Map<number, number>;
maxCnt: number;
stacks: Map<number, number[]>;
constructor() {
this.cnt = new Map();
this.maxCnt = 0;
this.stacks = new Map();
}

push(val: number): void {
let valCnt: number = 1 + (this.cnt.get(val) || 0);
this.cnt.set(val, valCnt);

if (valCnt > this.maxCnt) {
this.maxCnt = valCnt;
this.stacks.set(valCnt, []);
}
this.stacks.get(valCnt)?.push(val);
}

pop(): number {
let res: number = this.stacks.get(this.maxCnt)?.pop()!;
this.cnt.set(res, this.cnt.get(res)! - 1);

if (this.stacks.get(this.maxCnt)?.length == 0) {
this.maxCnt -= 1;
}

return res;
}
}

0 comments on commit 686c2e9

Please sign in to comment.