FrontendInterviews.dev

Loading problem…

9. Memoization with LRU Cache

Medium•
Acceptance: 77.42%
•
🔓3/3 Pro unlocks today

This problem builds on memoization. Complete that first, then load your solution to continue.

Implement a memoize function with LRU (Least Recently Used) cache that limits cache size and evicts least recently used entries.

Requirements

1. Basic Functionality

  • Accept a function fn and cache size limit
  • Return a memoized version with LRU cache
  • Limit cache size to specified maximum
  • Evict least recently used entries when limit reached
  • Track access order for LRU eviction

Example Usage

const expensiveFn = (n) => n * 2;
const memoized = memoize(expensiveFn, 3);

memoized(1); // Cache: [1]
memoized(2); // Cache: [1, 2]
memoized(3); // Cache: [1, 2, 3]
memoized(4); // Cache: [2, 3, 4] (evicts 1, least recently used)
memoized(2); // Cache: [3, 4, 2] (moves 2 to end)

Constraints

  • Implement LRU cache eviction
  • Limit cache size to maxSize
  • Track access order
  • Evict least recently used when limit reached