Skip to content
advent of code 2023

day 15

lens library

approach

part 1 runs each step of the sequence through the custom hash (add the character code, multiply by 17, mod 256) and sums the results.

part 2 builds the 256 boxes by hand. each Box keeps its lenses in a doubly linked list with dummy head and tail nodes, plus a dict from label to node. = updates the focal length of an existing node or appends a new one; - looks the node up and unlinks it. the focusing power is computed by iterating each box's list in order.

the trick

a dict from label to linked-list node gives ordered boxes with constant-time removal.

python
def remove(self, label):
    if label in self.d:
        node = self.d[label]
        node.remove()
        del self.d[label]

def put(self, label, focal_length):
    if label in self.d:
        node = self.d[label]
        node.focal_length = focal_length
    else:
        node = Node(label, focal_length)
        self.d[label] = node
        self.list.append(node)