HASH-P5

An LRU cache

Practice 5 of 6Hashing7 tests

The problem

Build an LRU cache (lesson 7). It holds at most capacity keys, each with a value.

  • get(key) returns the value, or -1 if 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

  1. Hint 1Nudge
  2. Hint 2Approach Open hint 1 first
  3. Hint 3Pseudocode Open hint 2 first
  4. Worked solutionlast resort Opens after all 3 hints
Python waits for a wider screensolution.py

Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.

7 tests, not run yet
Test results
#TestResultReads · time
1Room for twoNot run
2Put updates and refreshesNot run
3Capacity oneNot run
4A miss changes nothingNot run
5get refreshesNot run
6Values can be falsyNot run
7200,000 operationsNot run