DesignTheSystem/dev
MEDIUM Low-Level Design (LLD) 12 automated tests

Design LRU Cache (Low-Level Design)

A fixed-size cache that throws out the least recently used entry when full, with every operation in constant time. Focus: Choosing data structures for constant-time operations.

DifficultyMEDIUM
Design focusChoosing data structures for constant-time operations
Automated grading3 public + 9 hidden tests (12 total)
Phase 2 follow-upEviction listeners and delete
LanguageTypeScript (OOP / Machine Coding)

Problem statement

Build a cache that holds at most `capacity` entries. Reading or writing a key makes it the most recently used.

When a new key is added to a full cache, the least recently used key is removed first.

get and put must take constant time: the hidden tests run tens of thousands of operations on a large cache within the time limit.

Functional requirements

  • new LRUCache(capacity) throws if capacity is less than 1.
  • get(key) returns the value or undefined, and marks the key as recently used.
  • put(key, value) adds or updates; updating never evicts.
  • keys() lists keys from most to least recently used; size() counts entries.

Required API & starter interface

Implement the TypeScript class interface below. You can add any helper classes, policies or strategies you need:

class LRUCache<V> {
  constructor(capacity: number) {}

  get(key: string): V | undefined {
    throw new Error("Not implemented");
  }

  put(key: string, value: V): void {
    throw new Error("Not implemented");
  }

  size(): number {
    throw new Error("Not implemented");
  }

  /** Most recently used first */
  keys(): string[] {
    throw new Error("Not implemented");
  }
}

Public test cases

Your code runs against 3 public tests plus 9 hidden edge-case tests in a sandbox:

Evicts the least recently used key (core)

var c = new LRUCache(2);
c.put("a", 1); c.put("b", 2); c.put("c", 3);
assertEqual(c.get("a"), undefined);
assertEqual(c.get("b"), 2);
assertEqual(c.get("c"), 3);

Reading a key protects it (core)

var c = new LRUCache(2);
c.put("a", 1); c.put("b", 2); c.get("a"); c.put("c", 3);
assertEqual(c.get("a"), 1);
assertEqual(c.get("b"), undefined);

Capacity must be positive (edge)

assertThrows(function () { new LRUCache(0); });

Design & structure checks

Beyond passing tests, the grader inspects your class structure for clean object-oriented design:

  • The cache's storage is private: If callers can reach the map or list directly, they can break the recency order and the cache stops being an LRU cache.

Phase 2: Change request

In real interviews, the follow-up tests whether your design is extensible. After your first version passes all 12 tests, you unlock the change request: Eviction listeners and delete.

Pair with High-Level System Design

Ready to scale LRU Cache across distributed servers? Try the matching HLD simulator problem: Design Distributed Cache.

Relevant low-level design lessons

More low-level design problems