interviewmind

LRU Cache

LRU Cache is a medium coding interview question. Design a cache that holds at most capacity keys and drops the least recently used one when it runs out of room. Below are examples, the constraints and 3 hints; press Practice and Dana, the interviewer, asks it out loud while you answer in TypeScript, Python, Java, C++ or Go.

Updated · By InterviewMind

Practice this question

Free in your browser, no account.

The problem

Coding · Medium

Design a cache that holds at most capacity keys and drops the least recently used one when it runs out of room.

get(key) returns the value, or -1 when the key isn’t there. put(key, value) inserts or updates a key. Reading or writing a key makes it the most recently used. Both run in O(1) time.

Example 1

Inputcapacity = 2 put(1, 1) · put(2, 2) · get(1) · put(3, 3) · get(2)Output1, -1

get(1) makes key 1 the most recent, so put(3, 3) evicts key 2.

Constraints

  • 1 ≤ capacity ≤ 3000
  • 0 ≤ key, value ≤ 10⁴
  • At most 2 · 10⁵ calls to get and put

Hints

Open one at a time, and try the question again after each.

Hint 1

A hash map finds a key in O(1), but it doesn’t remember the order keys were used in. You need a second structure that does, and that can move any key to the front in O(1).

Hint 2

Pair the hash map with a doubly linked list, most recently used at the head. The map points from each key to its node, so get and put can unlink a node and move it to the head without searching.

Hint 3

A put on a key that’s already there updates its value and moves it to the head without evicting anything. Dummy head and tail nodes spare you the special cases for an empty list.

Practice it out loud

In the practice room Dana reads the question aloud in your browser’s own voice, with captions, and you answer in the editor beside it, in TypeScript, Python, Java, C++ or Go. It can look like LeetCode, HackerRank, CoderPad or Codility, so the screen is the one you’ll meet. It’s free and needs no account. Run the InterviewMind desktop app beside it and it hears the question the way it hears a real call, so you can see what it would show you in the live round.

Practice this question

More coding questions

interviewmind

Clarity under pressure.

Download for macOSWindows

On an Intel Mac? Download for Intel