faster algorithm