Problem solution · Python

All O`one Data Structure

All O`one Data Structure: a Python solution using direct simulation. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Direct simulation
Source
walkccc LeetCode Solutions
Length
87 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Direct simulation

For All O`one Data Structure, the implementation follows the problem’s operations directly while maintaining only the state needed for the next decision.

  1. Translate each rule into one explicit state update.
  2. Maintain the invariant after every processed item.
  3. 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.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeAll O`one Data Structure · PythonPython
Use this to learn the idea, then write your own version.
from dataclasses import dataclass  @dataclassclass Node:  def __init__(self, count: int, key: str | None = None):    self.count = count    self.keys: set[str] = {key} if key else set()    self.prev: Node | None = None    self.next: Node | None = None   def __eq__(self, other) -> bool:    if not isinstance(other, Node):      return NotImplemented    return self.count == other.count and self.keys == other.keys  class AllOne:  def __init__(self):    self.keyToNode: dict[str, Node] = {}    self.head = Node(0)    self.tail = Node(0)    self.head.next = self.tail    self.tail.prev = self.head   def inc(self, key: str) -> None:    if key in self.keyToNode:      self._incrementExistingKey(key)    else:      self._addNewKey(key)   def dec(self, key: str) -> None:    # It is guaranteed that key exists in the data structure before the    # decrement.    self._decrementExistingKey(key)   def getMaxKey(self) -> str:    return '' if self.tail.prev == self.head \        else next(iter(self.tail.prev.keys))   def getMinKey(self) -> str:    return '' if self.head.next == self.tail \        else next(iter(self.head.next.keys))   def _addNewKey(self, key: str) -> None:    """Adds a new node with frequency 1."""    if self.head.next.count == 1:      self.head.next.keys.add(key)    else:      self._insertAfter(self.head, Node(1, key))    self.keyToNode[key] = self.head.next   def _incrementExistingKey(self, key: str) -> None:    """Increments the frequency of the key by 1."""    node = self.keyToNode[key]    node.keys.remove(key)    if node.next == self.tail or node.next.count > node.count + 1:      self._insertAfter(node, Node(node.count + 1))    node.next.keys.add(key)    self.keyToNode[key] = node.next    if not node.keys:      self._remove(node)   def _decrementExistingKey(self, key: str) -> None:    """Decrements the count of the key by 1."""    node = self.keyToNode[key]    node.keys.remove(key)    if node.count > 1:      if node.prev == self.head or node.prev.count != node.count - 1:        self._insertAfter(node.prev, Node(node.count - 1))      node.prev.keys.add(key)      self.keyToNode[key] = node.prev    else:      del self.keyToNode[key]    if not node.keys:      self._remove(node)   def _insertAfter(self, node: Node, newNode: Node) -> None:    newNode.prev = node    newNode.next = node.next    node.next.prev = newNode    node.next = newNode   def _remove(self, node: Node) -> None:    node.prev.next = node.next    node.next.prev = node.prev 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗