Skip to content
advent of code 2015

day 01

not quite lisp

approach

the input is one line of parentheses. a single pass keeps a running total, +1 for ( and -1 for ), and the same loop remembers the first position where the total goes negative.

part 1 is the final total. part 2 is that first position, counted from 1.

the trick

both answers come out of one pass: the running sum, and the first index where it dips below zero.

python
def solve(l):
    res = 0
    mn = None
    for i, c in enumerate(l, 1):
        res += 1 if c == "(" else -1
        if res < 0 and mn is None:
            mn = i
    return res, mn