Improved algorithm by not requiring creation of an additional list.