Part 2 is a brute-forced hack (7 seconds on my machine) but I'm not sure I want to spend the time to find a better solution.