better algo, doesn't time out