Replace O(n^2) duplicate check with O(n)