0
0
DSA Typescriptprogramming~3 mins

Why Memoization Top Down DP in DSA Typescript?

Choose your learning style9 modes available
The Big Idea

What if you could make your slow, repeating calculations instantly fast by just remembering past answers?

The Scenario

Imagine you are trying to solve a puzzle where you need to find the number of ways to climb stairs, but you keep recalculating the same steps over and over again.

Every time you reach a step, you start counting from scratch without remembering what you already solved.

The Problem

This manual way is slow because you repeat the same work many times.

It wastes time and can make your program take forever for big puzzles.

Also, it is easy to get confused and make mistakes when you do the same calculations again and again.

The Solution

Memoization with Top Down Dynamic Programming solves this by remembering answers to smaller problems.

When you solve a step, you save the result.

Next time you need that step, you just look it up instead of recalculating.

This makes your program much faster and easier to understand.

Before vs After
Before
function climbStairs(step: number): number {
  if (step <= 1) return 1;
  return climbStairs(step - 1) + climbStairs(step - 2);
}
After
const memo: number[] = [];
function climbStairs(step: number): number {
  if (step <= 1) return 1;
  if (memo[step] !== undefined) return memo[step];
  memo[step] = climbStairs(step - 1) + climbStairs(step - 2);
  return memo[step];
}
What It Enables

This technique enables solving complex problems efficiently by breaking them into smaller parts and remembering results.

Real Life Example

Calculating the Fibonacci sequence quickly is a classic example where memoization saves time by avoiding repeated calculations.

Key Takeaways

Manual repeated calculations are slow and error-prone.

Memoization stores results to avoid repeating work.

Top Down DP with memoization makes recursive solutions efficient.