The Kth Largest Element in a Stream interview question asks you to design a class that can handle a continuous flow of numbers. You need to provide an add(val) method that inserts a new number and returns the current largest element in the entire stream.
This is a flagship question for Design interview patterns and Priority Queues. Companies like Meta and Atlassian ask this to see if you can avoid sorting the entire list every time a new number is added (). The goal is to achieve time per addition by only keeping the "interesting" part of the data.
This problem is the quintessential use case for a Min-Heap.
add is , and show is ., initial stream [4, 5, 8, 2]
[4, 5, 8]. (2 was popped). largest is 4.add(3): Heap [3, 4, 5, 8] -> pop 3 -> [4, 5, 8]. Result: 4.add(5): Heap [4, 5, 5, 8] -> pop 4 -> [5, 5, 8]. Result: 5.add(10): Heap [5, 5, 8, 10] -> pop 5 -> [5, 8, 10]. Result: 5.add, which is .Remember the rule: "To find the largest, use a Min-Heap of size . To find the smallest, use a Max-Heap of size ." This is a fundamental Heap interview pattern.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Search in a Binary Search Tree | Easy | Solve | |
| Insert into a Binary Search Tree | Medium | Solve | |
| Binary Search Tree Iterator | Medium | Solve | |
| Inorder Successor in BST II | Medium | Solve | |
| Delete Node in a BST | Medium | Solve |