LRU Cache

Problem

Simulate a least-recently-used cache and return values for get operations.

Examples

Example 1
Input: {"capacity":2,"operations":[["put",1,1],["put",2,2],["get",1],["put",3,3],["get",2]]}
Output: [1,-1]
Example 2
Input: {"capacity":1,"operations":[["put",2,6],["get",2],["put",3,1],["get",2],["get",3]]}
Output: [6,-1,1]

Input and output use JSON-compatible values. For linked-list and tree questions, arrays represent the node structure as described above. Your code should implement solve(input).

Write your solutionImplement solve(input). Your draft is saved in this browser.
Advertisement

How to solve LRU Cache

Simulate a least-recently-used cache and return values for get operations. Track recency whenever keys are read or written. The reference implementation illustrates this approach; check the example and edge cases.

Time and space complexity

O(1) average time per operation using an ordered hash map.

Practise and improve

Choose JavaScript, TypeScript or Python, complete the starter code, then select Run Tests. Request a hint when you need guidance, or choose View solution and confirm if you would like to study the reference implementation.