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?
- A. [5, 1, 2] (most to least recently used: 2, 1, 5)
- B. [5, 1] (most to least recently used: same order)
- C. [2, 1, 5] (most to least recently used: 5, 1, 2)
- 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.
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- What is the postfix (Reverse Polish) form of the infix expression "(i + j) d - b / h", built with the standard stack-based conversion (^…
- Array [61, 75, 77, 8, 27, 29, 31, 32, 47, 56] is a sorted array rotated at pivot 7. Using the standard O(log n) rotated-array binary…
- Using a sliding window (shrink from the left whenever more than k distinct characters are in the window), what is the length of the…
- Elevation map [2, 2, 5, 0, 2, 0, 3, 1, 1, 1] (bar width 1). Using the two-pointer / prefix-max approach for trapping rain water, how much…
- Using a sliding window of fixed size with a character-frequency count, how many substrings of "BAAAABBAACB" are anagrams of "AB"?
- A queue is implemented with two stacks (enqueue pushes to stack "in"; dequeue pops from stack "out", refilling "out" from "in" by…