I'm worried that the `sort` here increases time complexity. Benchmarks needed.