- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 87 lines of Python from the credited upstream file 432.py.
- The implementation visibly relies on hash lookup, ordered lookup.
- No explicit loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1from dataclasses import dataclass2 3 4@dataclass5class Node:6 def __init__(self, count: int, key: str | None = None):7 self.count = count8 self.keys: set[str] = {key} if key else set()9 self.prev: Node | None = None10 self.next: Node | None = None11 12 def __eq__(self, other) -> bool:13 if not isinstance(other, Node):14 return NotImplemented15 return self.count == other.count and self.keys == other.keys16 17 18class AllOne:19 def __init__(self):20 self.keyToNode: dict[str, Node] = {}21 self.head = Node(0)22 self.tail = Node(0)23 self.head.next = self.tail24 self.tail.prev = self.head25 26 def inc(self, key: str) -> None:27 if key in self.keyToNode:28 self._incrementExistingKey(key)29 else:30 self._addNewKey(key)31 32 def dec(self, key: str) -> None:33 34 35 self._decrementExistingKey(key)36 37 def getMaxKey(self) -> str:38 return '' if self.tail.prev == self.head \39 else next(iter(self.tail.prev.keys))40 41 def getMinKey(self) -> str:42 return '' if self.head.next == self.tail \43 else next(iter(self.head.next.keys))44 45 def _addNewKey(self, key: str) -> None:46 """Adds a new node with frequency 1."""47 if self.head.next.count == 1:48 self.head.next.keys.add(key)49 else:50 self._insertAfter(self.head, Node(1, key))51 self.keyToNode[key] = self.head.next52 53 def _incrementExistingKey(self, key: str) -> None:54 """Increments the frequency of the key by 1."""55 node = self.keyToNode[key]56 node.keys.remove(key)57 if node.next == self.tail or node.next.count > node.count + 1:58 self._insertAfter(node, Node(node.count + 1))59 node.next.keys.add(key)60 self.keyToNode[key] = node.next61 if not node.keys:62 self._remove(node)63 64 def _decrementExistingKey(self, key: str) -> None:65 """Decrements the count of the key by 1."""66 node = self.keyToNode[key]67 node.keys.remove(key)68 if node.count > 1:69 if node.prev == self.head or node.prev.count != node.count - 1:70 self._insertAfter(node.prev, Node(node.count - 1))71 node.prev.keys.add(key)72 self.keyToNode[key] = node.prev73 else:74 del self.keyToNode[key]75 if not node.keys:76 self._remove(node)77 78 def _insertAfter(self, node: Node, newNode: Node) -> None:79 newNode.prev = node80 newNode.next = node.next81 node.next.prev = newNode82 node.next = newNode83 84 def _remove(self, node: Node) -> None:85 node.prev.next = node.next86 node.next.prev = node.prev87