← Questions

LRU cache with runtime resizing

0
SnowflakeNvidiaCodingLast asked Feb 2026

A coding interview question asked in Nvidia's technical phone screen and at Snowflake, last asked Feb 2026. It tests design, hash map and linked list.

Implement a least recently used (LRU) cache whose capacity can change while it is in use.

class LRUCache:
    def __init__(self, capacity: int) -> None
    def get(self, key: int) -> int
    def put(self, key: int, value: int) -> None
    def resize(self, new_capacity: int) -> list[int]
  • get(key) returns the value for key, or -1 if it is not cached. A successful get makes the key the most recently used.
  • put(key, value) inserts or updates the key and makes it the most recently used. If the cache now holds more than capacity entries, evict the least recently used entry.
  • resize(new_capacity) changes the capacity. If the cache holds more entries than the new capacity, evict least recently used entries until it fits. Return the evicted keys, oldest first. Growing the capacity evicts nothing. Resizing does not count as using any key.

Constraints

  • get and put must run in O(1) time. resize may take time proportional to the number of entries it evicts.
  • Capacity may be 0 (the cache then stores nothing). A negative capacity is an error.
  • Up to 10^5 calls in total.

Example 1

LRUCache(3), put(1, 10), put(2, 20), put(3, 30), get(1) -> 10 (order from oldest: 2, 3, 1). put(4, 40) evicts key 2. resize(1) returns [3, 1] and leaves only key 4. resize(3) returns []. get(4) -> 40.

Example 2

LRUCache(2), put(1, 1), put(2, 2), put(1, 100) (update, no eviction), put(3, 3) evicts key 2, so get(2) -> -1 and get(1) -> 100.

Clarifying questions

  • Does put on an existing key in a zero-capacity cache do nothing?
  • Should resize to a negative capacity raise and leave the cache unchanged?
  • Does get of a missing key change any order?
  • Is thread safety required?

What a strong answer covers

  • Uses a hash map from key to node plus a doubly linked list ordered by recency (or OrderedDict with move_to_end and popitem(last=False)), giving O(1) get and put.
  • Evicts from the least recent end when size exceeds capacity; resize evicts in a loop and returns keys oldest first, O(evicted).
  • Handles capacity 0 (nothing stored, put is a no-op), updates without eviction, and shrinking below the current size.
  • Leaves recency order untouched on resize.
  • Tests Example 1's resize to 1 then 3, updates that refresh recency, capacity 0, and a negative capacity raising.

Follow-ups

  • Add a time to live per entry.
  • Make it thread-safe, and discuss lock contention (sharding by key).
  • Switch the policy to LFU, or evict by total size in bytes instead of entry count.

Where it's asked

What it tests

design · hash map · linked list · cache

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding