refactor algorithm to be faster and efficient