Design a Byte-Budgeted LRU Cache for Photo Thumbnails
Last updated: November 29, 2026
Quick Overview
Implement an LRU cache for decoded thumbnails whose limit is total bytes rather than entry count, and that can shrink on a memory-pressure warning.
Apple
November 29, 20260
0
0 solved
Implement an LRU cache for decoded thumbnails whose limit is total bytes rather than entry count, and that can shrink on a memory-pressure warning.
On iOS, apps get memory warnings and are terminated if they exceed limits, so a cache sized by item count is a classic bug when thumbnails vary in size. The interviewer checks LRU mechanics, byte accounting, and awareness of OS memory pressure.
What the Interviewer Expects
- Uses an ordered map (or hash map plus doubly linked list) for O(1) get and put
- Tracks total bytes and evicts from the least recently used end until the new item fits
- Handles replacing an existing key without double counting its size
- Rejects items larger than the whole budget instead of flushing the cache
- Adds a trim hook for memory warnings and mentions NSCache behavior
Key Topics to Cover
How to Approach This
- Apply SOLID principles. Single Responsibility makes code testable, Open/Closed makes it extensible.
- Choose data structures based on access patterns, not familiarity.
- Prefer immutable data and message passing over shared mutable state for concurrency.
- Design APIs with RESTful conventions, versioning, meaningful errors, and pagination from day one.
Possible Follow-up Questions
- How would you make this thread-safe without serializing every read?
- When would NSCache be a better choice, and what does it not guarantee?
- How would you choose the budget across iPhone models with different RAM?
- How would you add a disk tier for thumbnails evicted from memory?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice System Design ProblemsSample Answer
Requirements
get(id)returns bytes or None and marks the entry recently used.put(id, data)inserts, evicting least recently used entries until total bytes fit.trim(target)shrinks the cache when the ...
High-Level Design
Python's OrderedDict gives a hash map with a linked order, so move_to_end and popitem(last=False) are O(1). In Swift I would build the same with a dictionary of nodes in a doubly linked list. Th...