Used HashSet and refactored the code according to the comments
Used HashSet and refactored the code as per the comments.