Switch from O(n²) to O(n) duplicate detection