InterviewQuestions

InterviewQuestions
Edmend ZhangChapter 7: Heap + Top K + Monotonic Stack
1. Heap
Use Case:
Find the largest or smallest number among N elements.
- Push / Pop:
O(log N) - Peek:
O(1)
Common Problems:
- Top K Problem:
- Find Kth largest → use Min Heap
- Find Kth smallest → use Max Heap
Example Problems:
- Merge k Sorted Lists
- Find Median from Data Stream
- Kth Smallest Element in a Sorted Matrix
- Find K Pairs with Smallest Sums
- Reorganize String
Top K Examples:
- Kth Largest Element in an Array
- Top K Frequent Words
2. Monotonic Stack
Concept:
Find the first smaller/larger element in O(N) time.
- Monotonic Increasing Stack: find the first smaller value for each element.
- Monotonic Decreasing Stack: find the first larger value for each element.
Example Problems:
- Next Greater Element I
- Next Greater Element II
- Daily Temperatures
3. Python Templates
Heap (Top K Frequent Words):
1 | maps = {} |
Monotonic Stack:
1 | stack = [] |
4. Java Templates
Heap (Top K Frequent Words):
1 | PriorityQueue<Item> pq = new PriorityQueue<>((x1, x2) -> { |
Monotonic Stack:
1 | Deque<Integer> stack = new ArrayDeque<>(); |
Comment
匿名评论隐私政策
✅ 你无需删除空行,直接评论以获取最佳展示效果












