Changing implementation of duplicate removal to use an iterator