completed collapseDuplicates method