Python 3D Academyবাংলা

Designing Data Structures in Python

Chapter 63: Designing Data Structures

6 short lessons, with 3D animations, quizzes and coding tasks.

The lessons

  1. LRU cache: a dict plus a linked list

    An LRU cache (least recently used) keeps at most capacity items, moves an item to the front every time it is read or written, and when it overflows throws out the item at the back, the one used longest ago.

  2. Min stack and a hit counter

    Design the data so that each question is answered by looking in one place: a min stack writes, next to every item, the smallest item from the bottom up to it, and a hit counter keeps the hit times in a deque, oldest at the front, and drops the old ones from the front.

  3. A time-based key-value store

    A time-based key-value store keeps, for every key, its values with the times they were set; to answer "what was the value at time t?" it binary-searches that key's sorted list of times for the last one at or before t.

  4. Insert, delete and pick at random, all in O(1)

    Keep the values in a list for fair random picks, and a dict from each value to its index, so a removal can find the value at once and fill its gap with the last item of the list, which never shifts anything.

  5. The LFU cache: forget what is used least

    Count the uses of every key, keep the keys in groups by their count (each group ordered from least to most recently used), and remember the smallest count, so the key to remove is always the first one in the smallest group.

  6. Final project: a route planner for city buses

    Store the bus network as a graph (stops are vertices, bus legs are weighted edges), answer "fewest legs" with BFS (Chapter 51), "cheapest fare" with Dijkstra (Chapter 54), and rebuild the actual route by remembering where each stop was reached from.