← JavaScript Coding

LRU Cache

mediummapcachedata-structures
Asked at
Amazon
Cloudflare
Datadog
Google
Microsoft
Amazon, Cloudflare, Datadog, Google, Microsoft

Problem statement

Implement an LRUCache class. LRU means least recently used.

When the cache exceeds its capacity, it should evict the least recently used key.

API

const cache = new LRUCache(2);
cache.set('a', 1);
cache.set('b', 2);
cache.get('a'); // 1, now a is most recent
cache.set('c', 3); // evicts b

Requirements

  • get(key) returns the value or -1 when missing.
  • set(key, value) inserts or updates a key.
  • Both get and set should update recency.
  • Evict the least recently used key when size exceeds capacity.
  • Use O(1) average operations.

Requirements & constraints

  • →Capacity must be positive.
  • →Missing values return -1.
  • →Average get/set should be O(1).

How to approach LRU Cache

The strategy an interviewer expects you to reach for.

Approach JavaScript Map preserves insertion order. We can use that order as recency order by deleting and re-inserting a key whenever it is accessed.

Premium

The full solution is part of HelloFrontend Pro

The question above is free to read in full. Upgrade to unlock the interactive workspace and the senior-level walkthrough that go with it.

  • Runnable editor with the hidden test suite
  • Progressive hints that unlock as you get stuck
  • Senior-level reference solution with a line-by-line walkthrough
Unlock the full solution →

Already a member? Log in to open the workspace.

More JavaScript Coding questions

View all JavaScript Coding →
JS CodingMedium

Data Merging (Gym Sessions)

JS CodingHard

Data Selection

JS CodingEasy

Two Sum

JS CodingEasy

Contains Duplicate