LRU Cache

HardDesignDesign

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Design a data structure that follows the constraints of a **Least Recently Used (LRU) cache**. Implement the LRUCache class: - LRUCache(int capacity) Initialize the LRU cache with **positive** size capacity. - int get(int key) Return the value of the key if the key exists, otherwise return -1. - void put(int key, int value) Update the value of the key if the key exists. Otherwise, add the key-value pair to the cache. If the number of keys exceeds the capacity from this operation, **evict** the least recently used key. The functions get and put must each run in O(1) average time complexity.

Examples

Input: ["LRUCache","put","put","get","put","get","put","get","get","get"] [[2],[1,1],[2,2],[1],[3,3],[2],[4,4],[1],[3],[4]]
Output: [null,null,null,1,null,-1,null,-1,3,4]
LRUCache with capacity 2. After put(1,1), put(2,2), get(1)=1. After put(3,3), key 2 is evicted (LRU). get(2)=-1. After put(4,4), key 1 is evicted. get(1)=-1, get(3)=3, get(4)=4.

Constraints

  • 1 <= capacity <= 3000
  • 0 <= key <= 10^4
  • 0 <= value <= 10^5
  • At most 2 * 10^5 calls will be made to get and put.

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More Design problems