Improved logic for stopping duplicates and added test case