The optimization is described [here](https://stackoverflow.com/a/79306350/125349), with references to proofs of correctness and complexity.