Data Structures & AlgorithmsVery hardAmazon/Microsoft SDE pattern

An LRU cache of capacity 3 runs this sequence of operations in order: put(8, 80), put(8, 80), put(6, 60), put(7, 70), put(8, 80), put(1, 10). (get also marks a key as most-recently used.) What keys remain in the cache at the end, from least to most recently used?

  1. A. [7, 8] (most to least recently used: same order)
  2. B. [1, 8, 7] (most to least recently used: 7, 8, 1)
  3. C. [7, 8, 1] (most to least recently used: 1, 8, 7)
  4. D. [6, 7, 1] (most to least recently used: 1, 7, 6)

Correct answer: C. [7, 8, 1] (most to least recently used: 1, 8, 7)

An LRU cache evicts the least-recently-used key only when inserting a new key would exceed capacity, and every get or re-put of a key moves it to the most-recently-used end. Tracing the 6 operations in order leaves [7, 8, 1] (most to least recently used: 1, 8, 7). A FIFO policy (evict by insertion order, ignoring get) would instead leave [6, 7, 1] (most to least recently used: 1, 7, 6), which is a different (and wrong) eviction rule for LRU.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic