Skip to content
advanced

Counting paths with a memo

Complete the memoized staircase counter — the cache lookup, the cache write, and the table that holds them.

/**
 * Returns the number of distinct ways to climb `steps` stairs taking
 * 1 or 2 steps at a time. steps is a non-negative integer.
 */
export function countPaths(steps: number): number {
  const ____ = new Map<number, number>()

  function climb(remaining: number): number {
    if (remaining <= 1) return 1

    const cached = memo.___(remaining)
    if (cached !== undefined) return cached

    const paths = climb(remaining - 1) + climb(remaining - 2)
    memo.___(remaining, paths)
    return paths
  }

  return climb(steps)
}
0/3 filled tab moves · Ctrl+↵ submits · Ctrl+Shift+↵ runsstarter code