Updated the code with hashmap memoization