finish chapter 9: refactor to handle duplicates