Implement the given class FrequencyStack consisting of three functions :
FrequencyStack() : Creates a new FrequencyStack.
void push(int element) : Pushes the element onto the top of the stack.
int pop() : Returns and remove the most frequent element in the stack. If there are multiple elements with the same maximum frequency then return the integer which is closest to the stack top.
You will be given ‘q’ queries consisting of push and pop operation. In each query input is of following type :
0 : It means we have to pop the element with maximum frequency and return this element.
1 ‘element’ : It means we have to push ‘element’ onto the top of the stack.
Note: If a pop operation is used in an empty stack nothing happens to the stack, but you have to return -1.
The first line of the input contains ‘T’ denoting the number of test cases.
The first line of each test case contains ‘q’ denoting the number of queries.
In the next 'q' lines input is either of the types :
0 : It means you have to pop the element with maximum frequency and return this element.
1 ‘element’ : It means we have to push ‘element’ onto the top of the stack.
Output Format :
If the stack is non-empty return the removed element.
If a stack is empty return -1.
Print the output of each test case in a new line.
Note :
You do not need to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 50
0 <= q , element <= 5000
0 <= id <= 1
where 'id' denotes the type of query which is either 0 or 1.
Time Limit : 1 sec
1
7
0
1 3
1 3
1 2
1 2
0
0
-1
2
3
For the First test case :
Initially, stack is empty : {}
For the first query : pop operation :
Since the stack is empty return -1.
For the second query: push operation:
The stack is now : {3}
For the third query: push operation:
The stack is now : {3,3}
For the fourth query : push operation :
Stack is now : {2,3,3}
For the fifth query : push operation :
The stack is now : {2,2,3,3}
For the sixth query : pop operation :
Both 2 and 3 have the same frequency but 2 is
nearer to the top. Hence 2 is popped
Stack is now : {2,3,3}
For the seventh query : pop operation :
3 has a maximum frequency. Hence 3 is popped.
The stack is now : {2,3}
1
3
1 1
0
0
1
-1
Use hashmaps + stack to implement the stack.
Explanation:
The main idea is that we are concerned with the frequency of elements. So we create hashmaps to store its frequency of elements. Now to know which element is at top corresponding to the maximum frequency we create hashmaps of a frequency corresponding to stacks. It will help us to know the top element corresponding to the maximum frequency.
Algorithm:
O(q) where ‘q’ is the number of queries.
The pop and push operation takes O(1) time. Hence total time will be O(q). Here ‘q’ is the number of queries.
O(q) where ‘q’ is the number of queries.
To store the elements in maps. Hence it will take O(q) space. Here ‘q’ is the number of queries.