One Pager Cheat Sheet
- Yes, it is possible to implement a
LRU Cachewith the mentioned constraints, where theputandgetmethods have a time complexity ofO(1). - We are setting up a
cachethat has agetandputmethod using ahash tableand doublylinked listdata structurefor lookups and insertion in constant time. - We can dynamically construct a
DLinkedNodeand useaddNodeandremoveNodeto add and remove nodes to/from the head of a doubly linked list. - We need to
newup aCacheinstance with reference to the capacity, acountfor keys, thecacheitself, and references to the heads and tails of the doubly linked list. - We
putthe new value in thecacheand move it to the front of thedoubly linked listif it exists, or create a new node if it doesn't, as well as evict nodes from the tail if we're over capacity to ensure the order of use is maintained. - The
moveToHeadfunctionremovesandre-addsa node to the front of a list, letting us know it was the most recently used key. - We
getakeyfrom thecacheandmoveToHeadif found, otherwise return-1. - The
performanceof the bold newproductwas "not too bad".
This is our final solution.
To visualize the solution and step through the below code, click Visualize the Solution on the right-side menu or the VISUALIZE button in Interactive Mode.
xxxxxxxxxx99
}var assert = require('assert');​class Cache { constructor(capacity) { this.count = 0; this.capacity = capacity; this.cache = {}; this.head = new DLinkedNode(); this.head.pre = null; this.tail = new DLinkedNode(); this.tail.next = null; this.head.next = this.tail; this.tail.pre = this.head; }​ get(key) { const node = this.cache[key]; if (!node) { return -1; } this.moveToHead(node); return node.val; }​ put(key, value) { const node = this.cache[key]; if (!node) { const newNode = new DLinkedNode(key, value, null, null); this.cache[key] = newNode; this.addNode(newNode); this.count++; if (this.count > this.capacity) {OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment
Great job getting through this. Let's move on.
If you had any problems with this tutorial, check out the main forum thread here.


