Refactored containsDuplicate method