Design an LRU Cache

Last updated: March 3, 2025

Quick Overview

Design a Least Recently Used (LRU) Cache that supports the following operations: `get(key)` which retrieves the value of the key if it exists in the cache, and `put(key, value)` which updates or adds the key-value pair in the cache. The cache should evict the least recently used item when it exceeds its capacity, and both operations should run in O(1) time. The cache's capacity will be defined upon initialization.

ByteDance
Coding & Algorithms
Software Engineer
ByteDance
March 3, 2025
Software Engineer
Coding Round
Coding & Algorithms
Medium

10

3

4,565 solved


Design a Least Recently Used (LRU) Cache that supports the following operations: `get(key)` which retrieves the value of the key if it exists in the cache, and `put(key, value)` which updates or adds the key-value pair in the cache. The cache should evict the least recently used item when it exceeds its capacity, and both operations should run in O(1) time. The cache's capacity will be defined upon initialization.

Data structure design is a common ByteDance pattern. LRU cache appears frequently and tests combining hash maps with linked lists.

What the Interviewer Expects
  • Implement O(1) get and put operations
  • Use doubly-linked list and hash map combination
  • Handle capacity-based eviction correctly
  • Write clean, bug-free pointer manipulation code
  • Discuss real-world applications
Key Topics to Cover
LRU cache
Doubly-linked list
Hash map
Data structure design
O(1) operations
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • How would you implement this in a thread-safe way?
  • How would you add TTL expiration?
  • How would you make this distributed across multiple machines?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Problem Analysis

To implement an LRU Cache, we need to efficiently manage the storage of key-value pairs while ensuring that both retrieval (get) and insertion (put) operations run in O(1) time. The specific patte...

Approach
  1. Data Structures: Use a hash map (dict) to store key-node pairs and a doubly-linked list to maintain the order of usage. The head of the list will represent the most recently used item, while ...

Submit Your Answer
Markdown supported

Related Questions