As reported: DigitalOcean Staff Software Engineer loop (2025), coding round: design an LRU cache; the same round also had questions on database indexing, how HTTPS works and DNS resolution.
Design a data structure for a least recently used (LRU) cache with a fixed capacity.
LRUCache(capacity)— create the cache with a positive capacity.get(key)— return the value ofkeyif it is present, else-1. A successfulgetmakeskeythe most recently used.put(key, value)— insert or updatekey. If the insert makes the cache exceedcapacity, evict the least recently used key first.
get and put must each run in O(1) average time.
This is LeetCode 146 — LRU Cache.
Example
["LRUCache","put","put","get","put","get","put","get","get","get"]
[[2],[1,1],[2,2],[1],[3,3],[2],[4,4],[1],[3],[4]]
-> [null,null,null,1,null,-1,null,-1,3,4]
put(3,3) evicts key 2 (key 1 was just read); put(4,4) evicts key 1.
Constraints: 1 ≤ capacity ≤ 3000; 0 ≤ key ≤ 10^4; 0 ≤ value ≤ 10^5; at most 2 · 10^5 calls.
Code runner format: two lines, LeetCode's design format — the list of operation names and the list of argument lists. Implement the LRUCache class; the harness prints the list of results (null for the constructor and put).