a much simpler version of my nlogn solution, which is probably optimal for the phone screen