But verily my code, though logically correct, was not actually viable for part 2 within a reasonable span of time. So I wrote a fresh function with a different logic.
And this was in turn backwards-applicable to part 1, so I'm just sharing that function in the code snapshot here.