Implemented memoization and bug fixes