improved algorithm to not include unnecessary cases