Detecting duplicates and counting them only once