solution now handles duplicates