0% completed
Problem Challenge 3: Frequency Stack (hard)
.....
.....
.....
Anonymous
· 2 years ago
lets take this case 5,5,5,2,2,2,1,1,1
The output should be 5, 2, 1, 5, 2, 1, 5, 2, 1
initially all are the same but 5 got inserted first so it goes out. if we pop out 5 then we have more 2 and 2 got inserted before 1 then it gets popped out then 1
Here is my solution to the problem.
from heapq import * import sys class Element: def __init__(self, val, freq, time): self.val = val self.freq = freq self.time = time def __lt__(self, other): # compare the frequencies first then compare the time if self.freq < other.freq: return True elif self.freq > other.freq: return False else: return self.time < other.time class Solution: def __init__(self): self.max_heap = [] self.tracker = {} self.time =
Anonymous
· 3 years ago
Could we not just check the frequency there and decrement and if it's 0 not push it back onto the heap?
Anonymous
· 4 years ago
Why do we not need to push the element back onto the heap during the pop() method??
Anonymous
· 4 years ago
There's an optimal solution for this question using a 'stack of stacks' (more like a map of stacks) which runs in O(1) time instead of O(logn) time with this heap solution; both solutions have the same space complexity of O(n).
Although it doesn't follow this pattern, it may be useful to understand this alternate solution (see Leetcode Hard: 895. Maximum Frequency Stack).
Reading Progress
0%