Complete solution for exercise 18 gets correct answer on sample dataset, but incorrect for test datasets