6. Final Capstone Project
Capstone Project: O(1) LRU Cache & Weighted Dijkstra Route Planner
Build two iconic systems-and-interview architectures in Python: an O(1) Least Recently Used (LRU) Cache using OrderedDict/doubly-linked-list principles, and a weighted shortest-path Route Planner using heapq Dijkstra's algorithm.
- Implement an O(1) get/put LRU Cache preserving recency order
- Implement Dijkstra's shortest-path algorithm with heapq and path reconstruction
- Verify both systems end-to-end against edge cases in the live Python sandbox
Welcome to the final capstone of Python Data Structures, Algorithms & Interview Prep! Here you unite hash maps, linked ordering, adjacency lists, and priority queues to build two iconic systems-engineering architectures asked at senior technical interviews:
- An
O(1)LRU (Least Recently Used) Cache — combining a hash map + doubly linked ordering. - A Weighted Shortest-Path Route Planner (Dijkstra's Algorithm) — combining adjacency lists +
heapqpriority queues + parent backtracking.
Architecture 1: O(1) LRU Cache (Hash Map + Doubly Linked Ordering)
Hash Map Lookup — O(1)
Doubly Linked Order — O(1)
The dict finds any key in O(1), while the doubly linked order moves accessed keys to MRU and evicts the LRU tail in O(1).
Why Naive Approaches Fail
- Using a
listto track recency makes moving a cache-hit key to the endlist.remove(key)→O(n)! - Using a plain
dictalone givesO(1)lookup, yet cannot evict the oldest untouched key without scanning or maintaining recency links. - Combining Hash Map + Doubly Linked List gives
O(1)get(key),O(1)put(key, val), andO(1)eviction!
In standard Python, collections.OrderedDict implements that exact hash table + doubly linked list under the hood:
self._cache.move_to_end(key)promotes an accessed or updated key to Most Recently Used (MRU) inO(1).self._cache.popitem(last=False)evicts the Least Recently Used (LRU) key from the front inO(1).
Step-by-Step Dry-Run Trace (capacity = 2)
| Operation | Action & Recency Order (LRU -> MRU) | Return Value |
|---|---|---|
put(1, 100) | Insert 1: [1: 100] | — |
put(2, 200) | Insert 2: [1: 100, 2: 200] | — |
get(1) | Hit! Promote 1 to MRU: [2: 200, 1: 100] | 100 |
put(3, 300) | Insert 3, capacity > 2 → evict LRU 2! [1: 100, 3: 300] | — |
get(2) | Miss (2 was evicted) | -1 |
put(1, 150) | Update existing 1 and promote to MRU: [3: 300, 1: 150] | — |
Architecture 2: Weighted Route Planner (Dijkstra's Algorithm)
Unlike unweighted BFS (where every step costs 1), road networks have different travel times (weight >= 0). Dijkstra's Algorithm replaces the FIFO deque with a min-heap (heapq) so the globally cheapest unexplored node is always settled next in O((V + E) log V) time!
Step-by-Step Dry-Run Trace (Home -> Campus)
Roads: (Home, Park, 2), (Home, Station, 4), (Park, Station, 1), (Park, Cafe, 5), (Station, Campus, 7), (Cafe, Campus, 1).
Popped (cost, node) | Stale (cost > dist[node])? | Relaxed Neighbors (new_cost < dist[nxt]) | Updated dist |
|---|---|---|---|
(0, Home) | No | Park: 2, Station: 4 | Home:0, Park:2, Station:4 |
(2, Park) | No | Station: 2+1=3 < 4 (improved!), Cafe: 2+5=7 | Station:3, Cafe:7 |
(3, Station) | No | Campus: 3+7=10 | Campus:10 |
(4, Station) | Yes (4 > 3) → continue | Skipped! | — |
(7, Cafe) | No | Campus: 7+1=8 < 10 (improved!) | Campus:8 (parent[Campus]=Cafe) |
(8, Campus) | No (node == goal) | Stop! Reconstruct Home -> Park -> Cafe -> Campus | Cost 8 |
Edge Cases to Always Guard Against
- Stale heap entries (
if cost > dist.get(node, float("inf")): continue): Becauseheapqdoesn't supportdecrease_key, we push a newer shorter(3, "Station")alongside the older(4, "Station"). Skipping stale pops keeps correctness andO(E log V)speed intact! - Disconnected target (
goal not in dist): Return(-1, [])cleanly instead of raisingKeyError. - Start equals goal (
start == goal): Pops(0, start), breaks immediately, and returns(0, [start]). - Negative edge weights: Dijkstra assumes non-negative weights (
w >= 0); negative edges require Bellman-Ford (O(V · E)).
Updating an existing key with put(1, 150) counts as using that key! If you update self._cache[key] = value without calling self._cache.move_to_end(key), key 1 stays at the LRU position and gets evicted too early!
Under the hood, Python's collections.OrderedDict maintains a hash table + doubly linked list—giving you the canonical O(1) LRU Cache architecture cleanly in standard Python. In a whiteboard interview where stdlib OrderedDict isn't allowed, implement a Node(key, val, prev, next) doubly linked list with sentinel head / tail dummy nodes plus a dict[int, Node]!
Interactive Capstone Sandbox
Test both complete implementations (plus automated assert suites covering eviction, updates, disconnected graphs, and shortest paths) live right here:
Click “Run Code” to execute this snippet right in your browser.
Quick Checkpoints
Why does Dijkstra's algorithm include if cost > dist.get(node, float('inf')): continue right after popping from heapq?
Which two data structures combine to give an LRU Cache O(1) get() and O(1) put()?
Capstone Checklist & Next Steps
DSA Capstone Checklist
0/4 doneTake the Final Assessment next to test your Data Structures & Algorithms mastery and earn your certificate!