Duplicate Linked List and Simulate LRU Cache Operations
Data Structure DesignAuto-graded · 18 test casesLast updated
Tests linked list deep copying with arbitrary pointers and implementing an LRU cache with O(1) operations using hash maps and doubly-linked lists.
You are given a linked list representation and a sequence of cache operations to perform.
Part 1: Linked List Duplication
The linked list is represented by two parallel arrays:
values: the node values in orderrandom_indices: for each node, the index of the node its random pointer targets, ornullif it points nowhere
Create a deep copy of this list structure. Your copy must preserve all node values and maintain identical random pointer relationships, but use entirely separate node objects.
Part 2: LRU Cache Simulation
Execute a sequence of cache operations. Each operation is one of:
"init"with argument[capacity]: initialize an LRU cache with the given capacity"get"with argument[key]: retrieve the value associated with the key, or return-1if not present. Mark this key as recently used."put"with argument[key, value]: insert or update the key-value pair. Mark this key as recently used. If the cache exceeds capacity after insertion, evict the least recently used key.
Both get and put operations must run in O(1) average time.
Input Format
values: list of integers representing node values in orderrandom_indices: list where each element is either an integer index ornulloperations: list of operation namesarguments: list of argument lists, one per operation
Output Format
Return a list containing exactly three elements:
- The copied
valuesarray (same as input) - The copied
random_indicesarray (same as input) - A list of results from each operation:
Nonefor"init"and"put", the retrieved/returned value for"get"
Constraints
0 <= len(values) <= 10000 <= values[i] <= 10000random_indices[i]is eithernullor a valid index intovalues1 <= len(operations) <= 1000- The first operation is always
"init" 1 <= capacity <= 30000 <= key, value <= 10000
Examples
Example 1
Input: duplicate_list_and_execute_cache([7, 13, 11, 10, 1], [None, 0, 4, 2, 0], ['init', 'put', 'put', 'get', 'put', 'get', 'get', 'put', 'get', 'get', 'get'], [[2], [1, 1], [2, 2], [1], [3, 3], [2], [1], [4, 4], [1], [3], [4]])
Output: [[7, 13, 11, 10, 1], [None, 0, 4, 2, 0], [None, None, None, 1, None, -1, 1, None, 1, -1, 4]]
Example 2
Input: duplicate_list_and_execute_cache([], [], ['init', 'get', 'put', 'get'], [[1], [5], [5, 9], [5]])
Output: [[], [], [None, -1, None, 9]]
Example 3
Input: duplicate_list_and_execute_cache([1, 2], [1, 0], ['init', 'put', 'put', 'get', 'put', 'get', 'get'], [[1], [1, 10], [2, 20], [1], [3, 30], [2], [3]])
Output: [[1, 2], [1, 0], [None, None, None, -1, None, -1, 30]]
Hints
Hint 1
For the linked list copy: use a hash map to track the correspondence between original and cloned nodes, then wire pointers in a second pass.
Hint 2
For the LRU cache: combine a hash map for O(1) lookups with a doubly-linked list to maintain access order.
Hint 3
Use sentinel head and tail nodes in your doubly-linked list to avoid special cases when inserting or removing at boundaries.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem combines two classic data structure challenges into one function.
Linked List Duplication:
The list is already provided as arrays, so duplication is straightforward: create independent copies of both the values and random_indices arrays using Python's list copying.
LRU Cache Implementation: An LRU (Least Recently Used) cache requires tracking both key-value pairs and their access order. We need O(1) time for both lookup and reordering.
The solution uses Python's OrderedDict, which maintains insertion order and provides:
- O(1) key lookup via hashing
- O(1) removal and reinsertion to update order
- O(1) access to the oldest item via
popitem(last=False)
For each operation:
init: Create a fresh cache with the specified capacityget: If the key exists, remove it and reinsert it at the end (marking it as most recently used), then return its value. If missing, return -1.put: If the key exists, remove it first. Insert the key-value pair at the end. If this exceeds capacity, remove the oldest item (first in the OrderedDict).
Why It Works:
The OrderedDict maintains keys in access order. The most recently accessed key is always at the end, and the least recently accessed is at the front. When capacity is exceeded, we evict from the front. Every access (whether get or put) moves the key to the end by removing and reinserting it.
Complexity
- Time: O(1) average for each
getandputoperation due to hash table lookups and OrderedDict's efficient reordering. Overall O(m) where m is the number of operations. - Space: O(capacity) for the cache structure, plus O(n) for the copied arrays where n is the list length.
Solution
from collections import OrderedDict
from typing import List, Optional
def duplicate_list_and_execute_cache(values: List[int], random_indices: List[Optional[int]], operations: List[str], arguments: List[List[int]]) -> List:
# Part 1: Create copies of the list structure arrays
copied_values = list(values)
copied_random_indices = list(random_indices)
# Part 2: Execute LRU cache operations
cache = OrderedDict()
capacity = None
results = []
for operation, args in zip(operations, arguments):
if operation == "init":
capacity = args[0]
cache.clear()
results.append(None)
elif operation == "get":
key = args[0]
if key not in cache:
results.append(-1)
else:
# Move to end (most recently used)
value = cache.pop(key)
cache[key] = value
results.append(value)
elif operation == "put":
key, value = args
if key in cache:
# Remove old position
cache.pop(key)
cache[key] = value
# Evict least recently used if over capacity
while len(cache) > capacity:
cache.popitem(last=False)
results.append(None)
return [copied_values, copied_random_indices, results]