LeetCode 347 asks for k most frequent elements with a constraint: beat O(n log n). Learn why naive sort fails, how a min-heap of size k achieves O(n log k), and the elegant bucket sort insight that delivers true O(n) — with full visual dry run, common mistakes, and Python/JavaScript solutions for all three approaches.
Build the minimum spanning tree using Prim's algorithm: start from any vertex, greedily expand by always adding the minimum-weight crossing edge using a min-heap.
Advanced Dijkstra patterns: state-space Dijkstra for problems with extra constraints like K stops, fuel limit, or restricted nodes. The key is augmenting the state beyond just the node.
Find the minimum time to swim from (0,0) to (n-1,n-1) where you can only move to a cell when time >= cell value. Two approaches: Dijkstra O(n² log n) and binary search + BFS O(n² log n).
Find the minimum intervals to complete all tasks given cooldown n. Greedy with max-heap: always execute most frequent available task, idle only when forced.
Find the k most frequent elements using a max-heap or bucket sort. O(n) bucket sort approach using frequency as bucket index — faster than O(n log n) heap.
Calculate how much water can be trapped in a 3D height matrix. Uses a min-heap BFS starting from the boundary, always processing the lowest border cell to determine water trapped inside.
Design a simplified Twitter where users post tweets and follow each other, with getNewsFeed returning the 10 most recent tweets from followed users using a min-heap merge.
Design a search autocomplete system that returns top 3 historical queries matching the current prefix, sorted by frequency then lexicographically. Uses a Trie with per-node frequency maps.
Design a leaderboard that tracks player scores, supports score additions, top K sum queries, and player resets using a hashmap with sorted aggregation.
Maintain a running median from a data stream using two heaps: a max-heap for the lower half and a min-heap for the upper half, rebalancing after each insertion.