Refactored to use memoization