Can we use a HashSet here for O(1) checking of duplicates instead of O(n)?