Skip to content
advent of code 2022

day 06

tuning trouble

approach

the signal is scanned with a fixed-size window. a Counter holds the characters in the window, and a separate uniq counter tracks how many of them appear exactly once. sliding the window updates both in constant time: the character leaving and the one entering each adjust uniq depending on whether their count crosses 1. when uniq equals the window size, every character in it is distinct.

part 1 uses a window of 4 and part 2 a window of 14; the function is the same. benchmark.py times this version against a naive one that recounts the whole window at every step, and the rust version does the same incremental count with a 26-slot array.

the trick

keep a running count of characters that appear exactly once, so checking the window is O(1).

python
        if w[signal[i]] == 0:
            uniq += 1
        elif w[signal[i]] == 1:
            uniq -= 1
        w[signal[i]] += 1

        if uniq == size:
            return i