code refactoring of remove_dup_or_elem in leetcode