Design an LRU cache that can serialize and restore its state as JSON

Quick Overview

Design an LRU cache with constant-time get and put that can also serialize its state to JSON and restore it later. It tests pairing a hash map with a doubly linked list, keeping recency order across a save and restore, and making evictions after a restore match the original cache.

Design an LRU cache that can serialize and restore its state as JSON

Company: Midjourney

Role: Software Engineer

Category: Software Engineering Fundamentals

Difficulty: medium

Interview Round: Other

Design a data structure that follows the constraints of a Least Recently Used (LRU) cache and also supports serialization and deserialization of its state. The cache supports the usual `get` and `put` operations in `O(1)` average time. In addition, `serialize()` returns a JSON string capturing the capacity and the current key-value pairs in recency order (least recently used first, most recently used last). `deserialize(data)` restores the cache state from such a string, replacing any existing state. After deserialization, future evictions and recency updates must behave exactly as if the cache had been built by replaying the recorded order of insertions. Implement a class `LRUCacheSerializable(capacity)` with the following methods: - `get(key: int) -> int`: return the value associated with the key and mark it as most recently used. Return `-1` if the key is not present. - `put(key: int, value: int)`: insert or update the key-value pair, marking it as most recently used. If inserting exceeds capacity, evict the least recently used key. - `serialize() -> str`: return a JSON string of the form `{"capacity": c, "items": [[k, v], ...]}`, where `items` is ordered from least to most recently used. - `deserialize(data: str)`: replace the current cache state with the state encoded in a JSON string produced by `serialize`. In the examples, the first input line lists the calls in order and the second lists their arguments. The output has one entry per call, with `null` for the constructor and for calls that return nothing. Example 1: ```text Input: ["LRUCacheSerializable", "put", "put", "get", "serialize", "put", "get", "get"] [[2], [1, 1], [2, 2], [1], [], [3, 3], [2], [3]] Output: [null, null, null, 1, "{\"capacity\":2,\"items\":[[2,2],[1,1]]}", null, -1, 3] Explanation: cache = LRUCacheSerializable(2) # capacity = 2 cache.put(1, 1) # cache (LRU->MRU): [(1,1)] cache.put(2, 2) # cache (LRU->MRU): [(1,1), (2,2)] cache.get(1) # -> 1 (1 becomes MRU; cache: [(2,2), (1,1)]) cache.serialize() # -> '{"capacity":2,"items":[[2,2],[1,1]]}' cache.put(3, 3) # evicts key 2 (LRU); cache: [(1,1), (3,3)] cache.get(2) # -> -1 (key 2 was evicted) cache.get(3) # -> 3 ``` Example 2 restores a snapshot over existing state, including a different capacity, and then keeps updating recency from the restored order. ```text Input: ["LRUCacheSerializable", "put", "deserialize", "get", "get", "put", "get", "serialize"] [[1], [5, 5], ["{\"capacity\":2,\"items\":[[3,30],[4,40]]}"], [5], [3], [6, 60], [4], []] Output: [null, null, null, -1, 30, null, -1, "{\"capacity\":2,\"items\":[[3,30],[6,60]]}"] Explanation: cache = LRUCacheSerializable(1) # capacity = 1 cache.put(5, 5) # cache (LRU->MRU): [(5,5)] cache.deserialize('{"capacity":2,"items":[[3,30],[4,40]]}') # old state replaced; capacity = 2; cache: [(3,30), (4,40)] cache.get(5) # -> -1 (key 5 belonged to the replaced state) cache.get(3) # -> 30 (3 becomes MRU; cache: [(4,40), (3,30)]) cache.put(6, 60) # evicts key 4 (LRU); cache: [(3,30), (6,60)] cache.get(4) # -> -1 (key 4 was evicted) cache.serialize() # -> '{"capacity":2,"items":[[3,30],[6,60]]}' ``` ```hint Constant-time recency A hash map finds entries quickly but cannot tell you which one is oldest. Pair it with a structure where moving an entry to one end and removing an entry from the other end both take constant time. ``` ```hint Restoring the order Some operation you already wrote places an entry at the most recent end. Think about the order in which to feed the saved pairs to it. ``` ### Constraints & Assumptions - `1 <= capacity <= 10^4` - `0 <= key, value <= 10^5` - At most `10^5` total calls across `get`, `put`, `serialize` and `deserialize`. - Serialized format: a JSON object `{"capacity": int, "items": [[key, value], ...]}` where `items` is ordered from least to most recently used. The examples use the compact form, with no spaces and `capacity` before `items`. ### Clarifying Questions to Ask - Must `serialize` produce exactly the compact string shown in the examples, or is any JSON that `deserialize` accepts good enough? - Does `serialize` count as an access to every key, or must it leave recency unchanged? - Will `deserialize` only ever receive strings produced by `serialize`, or should it reject malformed input or a snapshot with more items than its capacity? ### What a Strong Answer Covers - The pair of structures that gives `O(1)` average `get` and `put`, and how each operation updates recency. - When eviction happens, and how updating an existing key differs from inserting a new one. - How `serialize` walks the entries and produces deterministic JSON in least-to-most-recent order without changing recency. - How `deserialize` discards the old state and rebuilds the order so later evictions match a replay of the recorded order. - The time and space cost of each method. ### Follow-up Questions - Values are now large. How would you write the snapshot to disk without building one big string in memory? - How would you make the cache safe to call from several threads, and what should `serialize` see while writes continue? - How would you version the format so old snapshots still load after you add a TTL to each entry? - What should `deserialize` do with a snapshot that holds more items than its capacity?

Overview: Design an LRU cache with constant-time get and put that can also serialize its state to JSON and restore it later. It tests pairing a hash map with a doubly linked list, keeping recency order across a save and restore, and making evictions after a restore match the original cache.

Midjourney logo
Midjourney
Nov 25, 2026
mediumSoftware EngineerOtherSoftware Engineering Fundamentals
0
0

Design a data structure that follows the constraints of a Least Recently Used (LRU) cache and also supports serialization and deserialization of its state.

The cache supports the usual get and put operations in O(1) average time. In addition, serialize() returns a JSON string capturing the capacity and the current key-value pairs in recency order (least recently used first, most recently used last). deserialize(data) restores the cache state from such a string, replacing any existing state.

After deserialization, future evictions and recency updates must behave exactly as if the cache had been built by replaying the recorded order of insertions.

Implement a class LRUCacheSerializable(capacity) with the following methods:

  • get(key: int) -> int : return the value associated with the key and mark it as most recently used. Return -1 if the key is not present.
  • put(key: int, value: int) : insert or update the key-value pair, marking it as most recently used. If inserting exceeds capacity, evict the least recently used key.
  • serialize() -> str : return a JSON string of the form {"capacity": c, "items": [[k, v], ...]} , where items is ordered from least to most recently used.
  • deserialize(data: str) : replace the current cache state with the state encoded in a JSON string produced by serialize .

In the examples, the first input line lists the calls in order and the second lists their arguments. The output has one entry per call, with null for the constructor and for calls that return nothing.

Example 1:

Input:
["LRUCacheSerializable", "put",  "put",  "get", "serialize", "put",  "get", "get"]
[[2],                    [1, 1], [2, 2], [1],   [],          [3, 3], [2],   [3]]

Output: [null, null, null, 1, "{\"capacity\":2,\"items\":[[2,2],[1,1]]}", null, -1, 3]

Explanation:
cache = LRUCacheSerializable(2)        # capacity = 2
cache.put(1, 1)                        # cache (LRU->MRU): [(1,1)]
cache.put(2, 2)                        # cache (LRU->MRU): [(1,1), (2,2)]
cache.get(1)                           # -> 1    (1 becomes MRU; cache: [(2,2), (1,1)])
cache.serialize()                      # -> '{"capacity":2,"items":[[2,2],[1,1]]}'
cache.put(3, 3)                        # evicts key 2 (LRU); cache: [(1,1), (3,3)]
cache.get(2)                           # -> -1   (key 2 was evicted)
cache.get(3)                           # -> 3

Example 2 restores a snapshot over existing state, including a different capacity, and then keeps updating recency from the restored order.

Input:
["LRUCacheSerializable", "put",  "deserialize",                                    "get", "get", "put",    "get", "serialize"]
[[1],                    [5, 5], ["{\"capacity\":2,\"items\":[[3,30],[4,40]]}"],   [5],   [3],   [6, 60],  [4],   []]

Output: [null, null, null, -1, 30, null, -1, "{\"capacity\":2,\"items\":[[3,30],[6,60]]}"]

Explanation:
cache = LRUCacheSerializable(1)        # capacity = 1
cache.put(5, 5)                        # cache (LRU->MRU): [(5,5)]
cache.deserialize('{"capacity":2,"items":[[3,30],[4,40]]}')
                                       # old state replaced; capacity = 2; cache: [(3,30), (4,40)]
cache.get(5)                           # -> -1   (key 5 belonged to the replaced state)
cache.get(3)                           # -> 30   (3 becomes MRU; cache: [(4,40), (3,30)])
cache.put(6, 60)                       # evicts key 4 (LRU); cache: [(3,30), (6,60)]
cache.get(4)                           # -> -1   (key 4 was evicted)
cache.serialize()                      # -> '{"capacity":2,"items":[[3,30],[6,60]]}'

Constraints & Assumptions

  • 1 <= capacity <= 10^4
  • 0 <= key, value <= 10^5
  • At most 10^5 total calls across get , put , serialize and deserialize .
  • Serialized format: a JSON object {"capacity": int, "items": [[key, value], ...]} where items is ordered from least to most recently used. The examples use the compact form, with no spaces and capacity before items .

Clarifying Questions to Ask Guidance

  • Must serialize produce exactly the compact string shown in the examples, or is any JSON that deserialize accepts good enough?
  • Does serialize count as an access to every key, or must it leave recency unchanged?
  • Will deserialize only ever receive strings produced by serialize , or should it reject malformed input or a snapshot with more items than its capacity?

What a Strong Answer Covers Guidance

  • The pair of structures that gives O(1) average get and put , and how each operation updates recency.
  • When eviction happens, and how updating an existing key differs from inserting a new one.
  • How serialize walks the entries and produces deterministic JSON in least-to-most-recent order without changing recency.
  • How deserialize discards the old state and rebuilds the order so later evictions match a replay of the recorded order.
  • The time and space cost of each method.

Follow-up Questions Guidance

  • Values are now large. How would you write the snapshot to disk without building one big string in memory?
  • How would you make the cache safe to call from several threads, and what should serialize see while writes continue?
  • How would you version the format so old snapshots still load after you add a TTL to each entry?
  • What should deserialize do with a snapshot that holds more items than its capacity?