Problem · Design

LRU Cache for Query Results

MediumAmazon logoAmazonNEW GRADPHONE SCREEN
See Amazon hiring insights

Problem statement

Maintain a cache with positive integer capacity. Process each operation atomically in the supplied completed serialization order:

  • [1, key] performs get(key). Return the stored value, or -1 when the key is absent. A successful get makes the key most recently used.
  • [2, key, value] performs put(key, value). Insert or update the key and make it most recently used. Updating an existing key does not change the cache size. If an insertion exceeds capacity, evict exactly the least recently used key.

Return one string per operation: the decimal result of each get and the literal string "null" for each put. Implement both operations in O(1) expected time.

The problem statement continues
Pro

Examples

Example 1

capacity = 2operations = [[2,1,10],[2,2,20],[1,1],[2,3,30],[1,2],[1,3]]return = ["null","null","10","null","-1","30"]

Reading key 1 makes it recent, so inserting key 3 evicts key 2.

FastPrep Pro
Reported in 1 Amazon interview this week

Unlock this recently reported problem

FastPrep Pro gives you full access to interview problems reported within the last week.

  • Full problem statement and constraints
  • 1 more worked example, explained
  • Guided hints and editorial
  • Run your code on real test cases
$9/month

Pro subscription, billed yearly — or $19 month-to-month. Cancel anytime.

Free plan — 2 of 2 free unlocks used this week
CodePython 3
Run and Submit unlock with Pro
FastPrep Pro
Reported in 1 Amazon interview this week

Unlock this recently reported problem

FastPrep Pro gives you full access to interview problems reported within the last week.

  • Full problem statement and constraints
  • 1 more worked example, explained
  • Guided hints and editorial
  • Run your code on real test cases
$9/month

Pro subscription, billed yearly — or $19 month-to-month. Cancel anytime.

Free plan — 2 of 2 free unlocks used this week