Build an LFU Cache for Product Detail Page Fragments

Last updated: November 29, 2026

Quick Overview

Design a cache with fixed capacity that supports get and put in O(1) time and, when full, evicts the least frequently used key, breaking ties by least recent use.

Amazon
Coding & Algorithms
Software Engineer
Amazon
November 29, 2026
Software Engineer
Onsite
Coding & Algorithms
Hard

0

0

0 solved


Design a cache with fixed capacity that supports get and put in O(1) time and, when full, evicts the least frequently used key, breaking ties by least recent use.

Product detail pages on Amazon assemble many cached fragments, and frequency-based eviction keeps perennial best sellers warm. Interviewers expect frequency buckets of doubly linked lists plus a min-frequency pointer, and they probe the tie-breaking and min-frequency update rules.

What the Interviewer Expects
  • Map each key to a node holding value and frequency
  • Group nodes by frequency in doubly linked lists ordered by recency
  • Track the minimum frequency so eviction is O(1)
  • Reset min frequency to 1 on every new insert
  • Handle capacity zero and updates to existing keys
Key Topics to Cover
doubly linked lists
hash maps
cache eviction
LFU
O(1) design
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 add time-based expiry so stale fragments are evicted first?
  • How does LFU behave when popularity shifts suddenly, and how would frequency decay help?
  • How would you make this thread-safe without a single global lock?
Sharpen Your Skills on Codemia

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

Practice DSA Problems
Sample Answer
Requirements

Operations: get(key) returns the value or -1 and counts as a use; put(key, value) inserts or updates and also counts as a use. When inserting a new key into a full cache, evict the key with the lo...

High-Level Design

Keep nodes: key -> Node(key, val, freq) and buckets: freq -> doubly linked list, where the front of each list is the most recent use. A min_freq integer records the smallest frequency present. T...


Submit Your Answer
Markdown supported