Made algorithm faster