Design a stack-like data structure to push elements to the stack and pop the most frequent element from the stack.
Implement the FreqStack class:
FreqStack() constructs an empty frequency stack.void push(int val) pushes an integer val onto the top of the stack.int pop() removes and returns the most frequent element in the stack.Example 1:
Input
["FreqStack", "push", "push", "push", "push", "push", "push", "pop", "pop", "pop", "pop"]
[[], [5], [7], [5], [7], [4], [5], [], [], [], []]
Output
[null, null, null, null, null, null, null, 5, 7, 5, 4]
Explanation
2 * 104 calls will be made to push and pop.pop.The problem requires us to mimic a stack but with the constraint of popping the most frequent element. If there is a tie in frequency, the most recently pushed element should be popped first.
A basic approach is to maintain a simple stack and a frequency counter dictionary to keep track of the element count. On popping, we traverse the stack from top to bottom to find the element with the maximum frequency.
push(val): O(1) each time we push an element.pop(): O(n) since we have to traverse the whole stack to find the element with the maximum frequency.To optimize, we can use two hash maps:
frequency to keep track of the number of occurrences of each element.group to organize elements by their frequency, where each index in group represents a stack of elements with that frequency.This ensures that when we are popping, we can instantly retrieve the most frequent and recent element by looking at the top element of the stack at the current maximum frequency.
push(val): O(1) since we just increment counters and update stacks.pop(): O(1) for directly accessing and popping from the stack of the maximum frequency.