Grok 4.1 Fast· xai
Frontier Reasoning Traces
Create a memory-efficient LRU cache with O(1) operations.
- User
Create a memory-efficient LRU cache with O(1) operations.
- Assistant
class Node: def __init__(self, key=0, val=0): self.key = key self.val = val self.prev = None self.next = None class LRUCache: def __init__(self, capacity: int): self.capacity = capacity self.cache = {} # key -> Node self.head = Node() # Sentinel head (most recently used) self.tail = Node() # Sentinel tail (least recently used) self.head.next = self.tail self.tail.prev = self.head def _add_node(self, node: Node) -> None: """Add node right after head (MRU position).""" node.prev = self.head node.next = self.head.next self.head.next.prev = node self.head.next = node def _remove_node(self, node: Node) -> None: """Remove node from DLL.""" prev_node = node.prev next_node = node.next prev_node.next = next_node next_node.prev = prev_node def _move_to_head(self, node: Node) -> None: """Move node to MRU position.""" self._remove_node(node) self._add_node(node) def get(self, key: int) -> int: if key in self.cache: node = self.cache[key] self._move_to_head(node) return node.val return -1 def put(self, key: int, value: int) -> None: if key in self.cache: node = self.cache[key] node.val = value self._move_to_head(node) else: new_node = Node(key, value) self.cache[key] = new_node self._add_node(new_node) if len(self.cache) > self.capacity: # Evict LRU (before tail) lru = self.tail.prev self._remove_node(lru) del self.cache[lru.key] # Example usage: # cache = LRUCache(2) # cache.put(1, 1) # Cache is {1=1} # cache.put(2, 2) # Cache is {1=1, 2=2} # cache.get(1) # Returns 1 # cache.put(3, 3) # Evicts key 2, Cache is {1=1, 3=3} # cache.get(2) # Returns -1 # cache.put(4, 4) # Evicts key 1, Cache is {4=4, 3=3} # cache.get(1) # Returns -1 # cache.get(3) # Returns 3 # cache.get(4) # Returns 4
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.