Linked Lists
64 / 170Linked ListsLesson 9 of 12About 54 min
Two structures, each covering the other's weakness. The most useful design pattern in the unit.
A read: look the key up in the dict. If absent, report a miss. If present, unlink the node and reinsert it at the most recent end, then return its value.
A write: if the key exists, update the value and move the node to the most recent end. If not, create a node, insert it at the most recent end, and record it in the dict. Then, if the size now exceeds the limit, unlink the node at the least recent end and delete its key from the dict.
Both are three or four lines once unlink and insert_after exist. Build those first.
Time for a single get or put on the cache, and total space for a cache holding at most k entries.
node = self.by_key[key] # dict lookupunlink(node) # constant, thanks to prev and nextinsert_after(self.head, node)return node.valueRead the constraints first and let them tell you what complexity is expected. Derive the approach, implement it, run the tests, and submit when it passes.