Bird
Raised Fist0
Interview Preptop-k-elementshardAmazonFacebookGoogle

Frequency Stack (Max Frequency First)

Choose your preparation mode4 modes available
📋
Problem

Imagine a social media platform where you want to show the most frequently interacted posts first, but if two posts have the same frequency, the most recent one should appear first.

Design a stack-like data structure that supports push and pop operations. The pop operation removes and returns the element with the highest frequency. If multiple elements have the same highest frequency, pop the most recently pushed one among them. Implement the class FreqStack with methods push(int val) and pop() that behave as described.

1 ≤ number of operations ≤ 10^5Values pushed are integers in the range [0, 10^9]pop() will only be called if the stack is non-empty
Edge cases: pop() called when only one element is present → returns that elementmultiple elements with same frequency pushed in different orders → pop returns most recentall elements have frequency 1 → pop returns most recently pushed element
</>
IDE
class FreqStack: def __init__(self): pass def push(self, val: int) -> None: pass def pop(self) -> int: passpublic class FreqStack { public FreqStack() {} public void push(int val) {} public int pop() { return 0; } }class FreqStack { public: FreqStack() {} void push(int val) {} int pop() { return 0; } };class FreqStack { constructor() {} push(val) {} pop() { return 0; } }
class FreqStack:
    def __init__(self):
        # Write your solution here
        pass
    def push(self, val: int) -> None:
        pass
    def pop(self) -> int:
        pass
public class FreqStack {
    public FreqStack() {
        // Write your solution here
    }
    public void push(int val) {
    }
    public int pop() {
        return 0;
    }
}
class FreqStack {
public:
    FreqStack() {
        // Write your solution here
    }
    void push(int val) {
    }
    int pop() {
        return 0;
    }
};
class FreqStack {
    constructor() {
        // Write your solution here
    }
    push(val) {
    }
    pop() {
        return 0;
    }
}
Coming soon
0/9
Common Bugs to Avoid
Wrong: Pop returns element with max frequency but ignores recency order.Not using stacks per frequency; popping any max frequency element instead of most recent.✅ Maintain a stack for each frequency and pop from the stack of current max frequency.
Wrong: Pop returns incorrect element when multiple pushes of same element occur.Frequency not incremented on repeated pushes of same element.✅ Increment frequency count on every push of the element.
Wrong: Pop returns elements in FIFO order instead of LIFO when frequencies tie.Not maintaining recency order within frequency groups.✅ Use stacks (LIFO) per frequency to maintain recency order.
Wrong: Solution times out on large inputs.Brute force approach scanning entire stack on each pop causing O(n^2) complexity.✅ Use frequency map and stacks per frequency for O(1) amortized push and pop.
✓
Test Cases
t1_01basic
Input["push(5)","push(7)","push(5)","push(7)","push(4)","push(5)","pop()","pop()","pop()","pop()"]
Expected[null,null,null,null,null,null,5,7,5,4]

After pushing, frequencies are: 5↓3, 7↓2, 4↓1. pop() returns 5 (highest freq), next pop returns 7 (freq 2), next pop returns 5 (freq 2 after previous pop), last pop returns 4.

t1_02basic
Input["push(1)","push(2)","push(3)","push(2)","push(1)","push(2)","push(5)","pop()","pop()","pop()","pop()"]
Expected[null,null,null,null,null,null,null,2,2,1,5]

Frequencies after pushes: 2↓3, 1↓2, 3↓1, 5↓1. pop() returns 2 (freq 3), next pop returns 2 (freq 2), next pop returns 1 (freq 2), last pop returns 5 (freq 1).

t2_01edge
Input["push(10)","pop()"]
Expected[null,10]

Only one element pushed and popped; pop returns that element.

t2_02edge
Input["push(1)","push(2)","push(3)","pop()","pop()","pop()"]
Expected[null,null,null,3,2,1]

All elements have frequency 1; pop returns most recently pushed elements in reverse order.

t2_03edge
Input["push(4)","push(4)","push(4)","push(4)","pop()","pop()","pop()","pop()"]
Expected[null,null,null,null,4,4,4,4]

All elements identical; pop returns the same element each time until empty.

t3_01corner
Input["push(1)","push(2)","push(1)","push(2)","push(1)","pop()","pop()","pop()","pop()","pop()"]
Expected[null,null,null,null,null,1,2,1,2,1]

Tests greedy trap: popping highest frequency element but must pop most recent among ties.

t3_02corner
Input["push(1)","push(1)","pop()","push(1)","pop()","pop()"]
Expected[null,null,1,null,1,1]

Tests 0/1 vs unbounded confusion: multiple pushes of same element increase frequency correctly.

t3_03corner
Input["push(5)","push(7)","push(5)","pop()","pop()","pop()"]
Expected[null,null,null,5,7,5]

Tests off-by-one errors in frequency updates and pop order.

t4_01performance
Input["push(1)","push(2)","push(3)","push(4)","push(5)","push(6)","push(7)","push(8)","push(9)","push(10)","push(1)","push(2)","push(3)","push(4)","push(5)","push(6)","push(7)","push(8)","push(9)","push(10)","push(1)","push(2)","push(3)","push(4)","push(5)","push(6)","push(7)","push(8)","push(9)","push(10)","push(1)","push(2)","push(3)","push(4)","push(5)","push(6)","push(7)","push(8)","push(9)","push(10)","push(1)","push(2)","push(3)","push(4)","push(5)","push(6)","push(7)","push(8)","push(9)","push(10)","pop()","pop()","pop()","pop()","pop()","pop()","pop()","pop()","pop()","pop()","pop()","pop()","pop()","pop()","pop()","pop()","pop()","pop()","pop()","pop()","pop()","pop()","pop()","pop()","pop()","pop()","pop()","pop()","pop()","pop()","pop()","pop()","pop()","pop()","pop()","pop()","pop()","pop()","pop()","pop()","pop()","pop()","pop()","pop()","pop()","pop()","pop()","pop()","pop()","pop()","pop()","pop()","pop()","pop()","pop()","pop()","pop()"]
⏱ Performance - must finish in 2000ms

n=100 operations with mixed pushes and pops; O(1) amortized approach must complete within 2 seconds.

Practice

(1/5)
1. You are given a list of words and need to find the top k words that appear most frequently, with ties broken by lexicographical order. Which algorithmic approach guarantees an optimal solution in terms of time complexity?
easy
A. Sort all unique words by frequency descending and lex order ascending, then pick top k
B. Use a dynamic programming approach to count frequencies and select top k
C. Use a greedy approach by repeatedly picking the most frequent word until k are chosen
D. Use bucket sort by frequency, then sort words lexicographically within each bucket, and collect top k

Solution

  1. Step 1: Understand frequency distribution

    Counting frequencies is straightforward, but sorting all words fully costs O(n log n).
  2. Step 2: Use bucket sort to group words by frequency

    Bucket sort groups words by frequency in O(n), then sorting lex order within buckets is efficient since buckets are smaller.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Bucket sort + lex sort within buckets achieves O(n) time [OK]
Hint: Bucket sort by frequency then lex sort is optimal [OK]
Common Mistakes:
  • Assuming full sort is optimal
  • Using DP for frequency counting
  • Greedy without sorting fails tie-break
2. Consider the following buggy Quickselect implementation. Which line contains the subtle bug that can cause incorrect results?
medium
A. Line 4: The comparison operator in the if condition inside partition
B. Line 7: The swap of nums[i] and nums[right]
C. Line 11: The base case check if left == right
D. Line 15: The recursive call when pivot_index < k

Solution

  1. Step 1: Identify partition logic

    Partition should move elements greater than pivot to the left for kth largest.
  2. Step 2: Locate bug

    The condition uses '<' instead of '>', reversing the order and breaking correctness.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Incorrect comparison flips partition logic [OK]
Hint: Partition comparison must match desired order (greater for kth largest) [OK]
Common Mistakes:
  • Using wrong comparison direction in partition
  • Confusing base case with recursion
  • Swapping wrong elements
3. What is the time complexity of the optimal algorithm that uses a prefix XOR matrix and a min-heap of size k to find the kth largest XOR coordinate value in an m x n matrix?
medium
A. O(m * n * k)
B. O(m * n * log k)
C. O(m^2 * n^2)
D. O(m * n + k * log(m * n))

Solution

  1. Step 1: Identify loops and heap operations

    The algorithm iterates over all m*n coordinates, computing prefix XOR in O(1) per cell.
  2. Step 2: Analyze heap operations per coordinate

    For each coordinate, heap operations (push or replace) take O(log k) time, since heap size is limited to k.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Overall complexity is O(m * n * log k), not O(m * n * k) or O(m^2 * n^2) [OK]
Hint: Heap operations cost log k, not linear in k [OK]
Common Mistakes:
  • Confusing k with n or m
  • Assuming sorting all values is needed
  • Ignoring heap operation cost
4. Suppose the problem changes: you must find the k closest points to the origin, but points can be repeated multiple times (i.e., duplicates allowed and must be counted separately). Which modification to the Quickselect approach correctly handles this scenario without increasing time complexity significantly?
hard
A. Use a max heap of size k to keep track of closest points, allowing duplicates naturally.
B. Use a min heap to store all points and pop k times to get closest points, handling duplicates automatically.
C. Sort all points by distance and then remove duplicates before returning the first k points.
D. Modify Quickselect to partition points by distance and include duplicates in the partitioning logic without skipping any points.

Solution

  1. Step 1: Understand duplicates impact

    Duplicates must be treated as distinct points; Quickselect partitions by distance and does not rely on uniqueness.
  2. Step 2: Modify partition to handle duplicates correctly

    Partition logic remains the same; all points, including duplicates, are compared and placed correctly without skipping.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Quickselect handles duplicates naturally if partitioning is correct [OK]
Hint: Quickselect partitions all points regardless of duplicates [OK]
Common Mistakes:
  • Using min heap instead of max heap
  • Removing duplicates before selection
  • Sorting all points unnecessarily
5. Suppose you want to find the top k frequent words but now words can be reused infinitely many times (like unlimited supply). Which modification to the optimal bucket sort approach correctly handles this scenario?
hard
A. This problem reduces to a knapsack variant; bucket sort no longer applies
B. Modify frequency counting to consider infinite reuse, then apply bucket sort as usual
C. Use a dynamic programming approach to count combinations of words for frequencies
D. Use a max heap keyed by frequency and word lex order, repeatedly pop top k elements

Solution

  1. Step 1: Understand infinite reuse impact

    Infinite reuse means frequency counts are not fixed; problem becomes combinatorial.
  2. Step 2: Recognize problem class change

    Top k frequent words with unlimited reuse resembles knapsack or coin change, not simple frequency counting.
  3. Step 3: Bucket sort no longer applies

    Bucket sort relies on fixed frequencies; dynamic programming or other combinatorial methods are needed.
  4. Final Answer:

    Option A -> Option A
  5. Quick Check:

    Infinite reuse breaks frequency counting assumptions [OK]
Hint: Infinite reuse changes problem class, bucket sort invalid [OK]
Common Mistakes:
  • Trying to reuse bucket sort with infinite counts
  • Ignoring combinatorial explosion
  • Assuming heap approach suffices
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard