Design a simple LRU (Least Recently Used) cache that supports get and put operations with O(1) time complexity for both.

分类: technical

难度: easy

标签:

答题技巧

["Requires combination of hash map + doubly linked list","Hash map for O(1) lookup, doubly linked list for O(1) move/delete","get: return -1 if not found, else move node to head (most recent)","put: if exists → update value & move to head; if not → add new, evict tail if full","Junior roles may accept explanation + pseudocode","In JavaScript, Map can be used directly (maintains insertion order)"]

参考答案

Core idea: - get(key) → if exists, return value and move key to most recent - put(key, value) → if exists, update and move to most recent; else add new, evict oldest when over capacity

Technical
Easy

Design a simple LRU (Least Recently Used) cache that supports get and put operations with O(1) time complexity for both.

97 views

Answer Tips

["Requires combination of hash map + doubly linked list","Hash map for O(1) lookup, doubly linked list for O(1) move/delete","get: return -1 if not found, else move node to head (most recent)","put: if exists → update value & move to head; if not → add new, evict tail if full","Junior roles may accept explanation + pseudocode","In JavaScript, Map can be used directly (maintains insertion order)"]

Sample Answer

Core idea: - get(key) → if exists, return value and move key to most recent - put(key, value) → if exists, update and move to most recent; else add new, evict oldest when over capacity

Start Mock Interview Practice

Improve your interview skills and confidence with AI mock interviews