~/problems
Problems
Basics first, then the classics, then company-style assessments. Every problem has tests you run right here; multi-level ones unlock as you go. See the roadmap.
Heaps and priority queues
heapq: top-k, k-way merge, two heaps for a running median.
Notes
Recognise it when: you need top-k, the k-th largest, merging k sorted streams, repeatedly taking the smallest or largest, or a running median.
heapq.nlargest(k, cnt, key=cnt.get) # top-k frequent
h = [] # size-k min-heap for k-th largest
for x in nums:
heapq.heappush(h, x)
if len(h) > k: heapq.heappop(h)
# k-way merge: (value, list_index, element_index)
Running median: a max-heap lo (stored negated) and a min-heap hi. Push to lo, move lo's max to hi, and rebalance so len(lo) >= len(hi).
Gotchas: heapq is a min-heap only, so negate for max. Add a tie-breaker to tuples so Python never compares the objects themselves. Building a heap with heapify is O(n).
15 problems
Interview roadmap
Heaps Top-k, merging streams, scheduling by time.
Heaps and priority queues guide
- Basics: the k smallest values with heapq basics py · c++ · java easy
- Help desk by urgency easy
- Top K Frequent Elements py · c++ · java easy
- Kth Largest Element in an Array py · c++ · java medium
- Merge K Sorted Lists py · c++ · java medium
- Find Median from Data Stream py · c++ · java medium
- Seniority queue at the grazing field py · c++ · java medium
- Balance pins across columns Pinterest py · c++ · java easy
- OA: Escape room leaderboard 2 levels Pinterest py · c++ · java medium
- Top ads in a time window Pinterest py · c++ · java easy
- Kth Largest Element in a Stream py · c++ · java easy
- Last Stone Weight py · c++ · java easy
- Design Twitter py · c++ · java medium
- Reorganize String py · c++ · java medium
- IPO py · c++ · java hard