LRU Cache Problem

LRU Cache Problem — ExecCode Medium DSA Practice

Solve the LRU Cache problem on ExecCode. Free online medium DSA practice in Design. Write and run code in Java, C++, Python — no signup required to run.

Problem description

Design a data structure that implements a Least Recently Used (LRU) cache. Implement the LRUCache class: - LRUCache(capacity): initialize with positive size capacity - get(key): return the value if the key exists, otherwise return -1 - put(key, value): update or insert the value; if capacity would be exceeded, evict the least recently used key Both get and put must run in O(1) average time.

Examples

Input {"operations": ["LRUCache", "put", "put", "get", "put", "get", "put", "get", "get", "get"], "values": [[2], [1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]]}; Output [None, None, None, 1, None, -1, None, -1, 3, 4]. Input {"operations": ["LRUCache", "put", "get", "put", "get", "get"], "values": [[1], [2, 1], [2], [3, 2], [2], [3]]}; Output [None, None, 1, None, -1, 2]. Input {"operations": ["LRUCache", "put", "put", "put", "get", "get"], "values": [[2], [1, 10], [2, 20], [3, 30], [1], [2]]}; Output [None, None, None, None, -1, 20]

Constraints

1 ≤ capacity ≤ 3000 At most 2×10⁵ calls.

Practice LRU Cache free on ExecCode. Browse DSA problems, topic map, and placement guides.