Faster algorithm