Problem 2 refactored using a hash to store terms