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.

6 min readUpdated 2026-11-30
In This Lesson
  • 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:

  1. An O(1) LRU (Least Recently Used) Cache — combining a hash map + doubly linked ordering.
  2. A Weighted Shortest-Path Route Planner (Dijkstra's Algorithm) — combining adjacency lists + heapq priority queues + parent backtracking.

Architecture 1: O(1) LRU Cache (Hash Map + Doubly Linked Ordering)

O(1) LRU Cache = Hash Map (dict) + Doubly Linked Order

Hash Map Lookup — O(1)

key 3→ MRU Node
key 1→ LRU Node

Doubly Linked Order — O(1)

LRU (Evict!)⇄[3: 300] (MRU)

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 list to track recency makes moving a cache-hit key to the end list.remove(key) → O(n)!
  • Using a plain dict alone gives O(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), and O(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) in O(1).
  • self._cache.popitem(last=False) evicts the Least Recently Used (LRU) key from the front in O(1).

Step-by-Step Dry-Run Trace (capacity = 2)

OperationAction & 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)NoPark: 2, Station: 4Home:0, Park:2, Station:4
(2, Park)NoStation: 2+1=3 < 4 (improved!), Cafe: 2+5=7Station:3, Cafe:7
(3, Station)NoCampus: 3+7=10Campus:10
(4, Station)Yes (4 > 3) → continueSkipped!—
(7, Cafe)NoCampus: 7+1=8 < 10 (improved!)Campus:8 (parent[Campus]=Cafe)
(8, Campus)No (node == goal)Stop! Reconstruct Home -> Park -> Cafe -> CampusCost 8

Edge Cases to Always Guard Against

  • Stale heap entries (if cost > dist.get(node, float("inf")): continue): Because heapq doesn't support decrease_key, we push a newer shorter (3, "Station") alongside the older (4, "Station"). Skipping stale pops keeps correctness and O(E log V) speed intact!
  • Disconnected target (goal not in dist): Return (-1, []) cleanly instead of raising KeyError.
  • 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)).
Forgetting to Promote on put() Update in LRUCache

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!

How OrderedDict Achieves O(1) — And What to Say on a Whiteboard

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:

Python 3Capstone: O(1) LRU Cache + Dijkstra Route Planner
Output

Click “Run Code” to execute this snippet right in your browser.

Quick Checkpoints

Check Your Understanding

Why does Dijkstra's algorithm include if cost > dist.get(node, float('inf')): continue right after popping from heapq?

Check Your Understanding

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 done

Take the Final Assessment next to test your Data Structures & Algorithms mastery and earn your certificate!