Implement an LRU Cache with TTL Support

Last updated: April 5, 2025

Quick Overview

Build a Least Recently Used cache that supports time-to-live expiration on entries, with O(1) get and put operations and lazy expiration cleanup.

Canva
Coding & Algorithms
Software Engineer
Canva
April 5, 2025
Software Engineer
Unassisted Coding
Coding & Algorithms
Medium

10

5

3,876 solved


Build a Least Recently Used cache that supports time-to-live expiration on entries, with O(1) get and put operations and lazy expiration cleanup.

Caching is essential at Canva's scale for reducing latency on template rendering, asset delivery, and permission checks. This question tests your ability to combine two classic data structure concepts (LRU eviction and TTL expiration) into a clean, performant implementation.

What the Interviewer Expects
  • Implement O(1) get and put using a hash map and doubly linked list
  • Add TTL support with lazy expiration on access
  • Handle capacity-based eviction when the cache is full
  • Write clean, production-quality code with proper error handling
Key Topics to Cover
Hash maps and doubly linked lists
LRU eviction policy
TTL-based expiration
Time complexity analysis
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 active cleanup of expired entries without blocking reads?
  • How would you make this thread-safe for concurrent access?
  • How would you instrument this cache with hit rate metrics?
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

The problem requires us to implement an LRU (Least Recently Used) cache that also supports TTL (time-to-live) for its entries. Given that both LRU eviction policy and TTL expiration are classic proble...

Approach
  1. Data Structures: Use a hash map (cache) to store key-value pairs, where the value is a node in a doubly linked list. Each node holds the key, value, and timestamp of when it was last accessed...

Submit Your Answer
Markdown supported

Related Questions