Fast solution using a type of memoization