The problem
Build an LRU cache (lesson 7). It holds at most capacity keys, each with a value.
get(key)returns the value, or-1if the key is not there. A successful get makes the key the most recently used.put(key, value)sets the value and makes the key the most recently used. If the key is new and the cache is full, first throw out the least recently used key.- Both methods must take O(1) time on average.
C = LRUCache(2)
C.put(1, 1); C.put(2, 2)
C.get(1) # 1 (now 2 is the least recently used)
C.put(3, 3) # throws out 2
C.get(2) # -1
collections.OrderedDict is switched off: build the two-way list yourself.
The tests make an object and call its methods in order. A test shows the list of calls, and compares the list of everything they returned (methods that return nothing give None).
Limits
- Capacity up to 50,000; up to 200,000 calls.
Builds on HASH-7 LRU cache.
Continue on a laptop
Practice runs Python in the browser and needs a keyboard and a wider screen. Read the problem and open hints here, then write your solution on a laptop. Progress is saved per browser for now, so hints opened here stay on this device.
Need a hint?0 of 3 opened
- Hint 1Nudge
- Hint 2Approach Open hint 1 first
- Hint 3Pseudocode Open hint 2 first
- Worked solutionlast resort Opens after all 3 hints
Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.
7 tests, not run yet
| # | Test | Result | Reads · time |
|---|---|---|---|
| 1 | Room for two | Not run | |
| 2 | Put updates and refreshes | Not run | |
| 3 | Capacity one | Not run | |
| 4 | A miss changes nothing | Not run | |
| 5 | get refreshes | Not run | |
| 6 | Values can be falsy | Not run | |
| 7 | 200,000 operations | Not run |