|
| 1 | +class FreqStack { |
| 2 | + |
| 3 | + Stack<Integer> stack; |
| 4 | + Stack<Integer> freqStack; |
| 5 | + Map<Integer, Integer> map; |
| 6 | + int maxFreq; |
| 7 | + |
| 8 | + public FreqStack() { |
| 9 | + stack = new Stack<>(); |
| 10 | + freqStack = new Stack<>(); |
| 11 | + map = new HashMap<>(); |
| 12 | + maxFreq = Integer.MIN_VALUE; |
| 13 | + } |
| 14 | + |
| 15 | + public void push(int x) { |
| 16 | + // Everytime increment the frequency of number being pushed in the stack |
| 17 | + map.put(x, map.getOrDefault(x, 0) + 1); |
| 18 | + stack.push(x); |
| 19 | + |
| 20 | + // Update maxFreq if it changes after the push operation |
| 21 | + if (maxFreq < map.get(x)) { |
| 22 | + maxFreq = map.get(x); |
| 23 | + } |
| 24 | + |
| 25 | + // Push maxFreq to the freqStack to keep track of maximum frequency after each push |
| 26 | + freqStack.push(maxFreq); |
| 27 | + } |
| 28 | + |
| 29 | + public int pop() { |
| 30 | + |
| 31 | + int ans = -1; |
| 32 | + |
| 33 | + // If the top element in stack has the highest frequency then just return it by popping it |
| 34 | + if (map.get(stack.peek()) == maxFreq) { |
| 35 | + int temp = stack.pop(); |
| 36 | + map.put(temp, map.getOrDefault(temp, 0) - 1); |
| 37 | + ans = temp; |
| 38 | + } |
| 39 | + // Traverse the stack till you find the element with frequency equal to maxFreq |
| 40 | + else { |
| 41 | + int count = 0; |
| 42 | + Stack<Integer> temp = new Stack<>(); |
| 43 | + int t = -1; |
| 44 | + |
| 45 | + while (!stack.empty()) { |
| 46 | + count++; |
| 47 | + t = stack.pop(); |
| 48 | + freqStack.pop(); |
| 49 | + |
| 50 | + if (map.get(t) == maxFreq) { |
| 51 | + map.put(t, map.getOrDefault(t, 0) - 1); |
| 52 | + break; |
| 53 | + } |
| 54 | + else { |
| 55 | + temp.push(t); |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + // Put back the elements in the stack except the element with frequency equal to maxFreq |
| 60 | + while (!temp.empty()) { |
| 61 | + stack.push(temp.pop()); |
| 62 | + } |
| 63 | + |
| 64 | + // The element with frequency equal to maxFreq |
| 65 | + ans = t; |
| 66 | + |
| 67 | + // Check if the freqStack had a value except the value for maxFreq which we popped |
| 68 | + int freqTemp = freqStack.isEmpty() ? 0 : freqStack.peek(); |
| 69 | + |
| 70 | + // Update freqStack |
| 71 | + while (count-- > 0) { |
| 72 | + freqStack.push(freqTemp); |
| 73 | + } |
| 74 | + } |
| 75 | + |
| 76 | + freqStack.pop(); |
| 77 | + |
| 78 | + // Update maxFreq |
| 79 | + maxFreq = stack.isEmpty() ? Integer.MIN_VALUE : freqStack.peek(); |
| 80 | + |
| 81 | + return ans; |
| 82 | + } |
| 83 | +} |
0 commit comments