Data Structures & AlgorithmsVery hardHCLTech · Wipro pattern

An LRU cache of capacity 3 runs this sequence of operations in order: put(4, 40), put(2, 20), put(5, 50), put(1, 10), put(1, 10), put(2, 20). (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. [5, 1, 2] (most to least recently used: 2, 1, 5)
  2. B. [5, 1] (most to least recently used: same order)
  3. C. [2, 1, 5] (most to least recently used: 5, 1, 2)
  4. D. [2, 5, 1] (most to least recently used: 1, 5, 2)

Correct answer: A. [5, 1, 2] (most to least recently used: 2, 1, 5)

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 [5, 1, 2] (most to least recently used: 2, 1, 5). A FIFO policy (evict by insertion order, ignoring get) would instead leave [2, 5, 1] (most to least recently used: 1, 5, 2), 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