Bird
Raised Fist0
DSA Javaprogramming~10 mins

Memoization to Optimize Recursion in DSA Java - Execution Trace

Choose your learning style10 modes available
Concept Flow - Memoization to Optimize Recursion
Start Recursive Call
↓
Check Memo for Result?
Yes→Return Memoized Result
No↓
Compute Result Recursively
↓
Store Result in Memo
↓
Return Computed Result
The flow shows how recursion first checks if the answer is already saved (memo). If yes, it returns it immediately. Otherwise, it computes, saves, and returns the result.
Execution Sample
DSA Java
int fib(int n, Map<Integer, Integer> memo) {
  if (n <= 1) return n;
  if (memo.containsKey(n)) return memo.get(n);
  int result = fib(n-1, memo) + fib(n-2, memo);
  memo.put(n, result);
  return result;
}
This code calculates Fibonacci numbers using recursion with memoization to avoid repeated calculations.
Execution Table
StepOperationnMemo BeforeRecursive CallsMemo AfterReturned Value
1fib(4) called4{}[fib(3), fib(2)]{}?
2fib(3) called3{}[fib(2), fib(1)]{}?
3fib(2) called2{}[fib(1), fib(0)]{}?
4fib(1) base case1{}none{}1
5fib(0) base case0{}none{}0
6fib(2) computed2{}none{2:1}1
7fib(1) base case1{2:1}none{2:1}1
8fib(3) computed3{2:1}none{2:1,3:2}2
9fib(2) memo hit2{2:1,3:2}none{2:1,3:2}1
10fib(4) computed4{2:1,3:2}none{2:1,3:2,4:3}3
11Return final result4{2:1,3:2,4:3}none{2:1,3:2,4:3}3
💡 All recursive calls resolved; memo contains results for n=2,3,4; final fib(4) = 3 returned.
Variable Tracker
VariableStartAfter Step 4After Step 6After Step 8After Step 10Final
n422344
memo{}{}{2:1}{2:1,3:2}{2:1,3:2,4:3}{2:1,3:2,4:3}
Returned Value?11233
Key Moments - 3 Insights
Why does the function check the memo before computing?
Because checking the memo (see Step 9) avoids repeating expensive recursive calls, saving time by returning stored results immediately.
What happens when the base case is reached?
At base cases (Steps 4 and 5), the function returns the known value directly without recursion, starting the memoization process.
How does memoization reduce the number of recursive calls?
Memoization stores results after first computation (Steps 6 and 8), so later calls (Step 9) reuse these results instead of recalculating.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the returned value at Step 8?
A1
B2
C3
D0
💡 Hint
Check the 'Returned Value' column at Step 8 in the execution_table.
At which step does the memo first get updated with a value?
AStep 6
BStep 4
CStep 9
DStep 2
💡 Hint
Look at the 'Memo After' column to see when the first key-value pair appears.
If memoization was not used, how would the recursive calls change at Step 9?
AFewer recursive calls would happen
BNo change, memo is not used here
CMore recursive calls would happen instead of returning memoized result
DThe function would return 0 immediately
💡 Hint
Step 9 shows a memo hit avoiding recursion; without memo, recursion repeats.
Concept Snapshot
Memoization stores results of recursive calls in a map.
Before computing, check if result exists in memo.
If yes, return it immediately to save time.
If no, compute recursively, store result, then return.
This avoids repeated work and speeds up recursion.
Full Transcript
Memoization optimizes recursion by saving results of function calls in a map called memo. When the function is called with a value n, it first checks if the result is already in memo. If yes, it returns that result immediately, avoiding repeated calculations. If not, it computes the result recursively, stores it in memo, and then returns it. This process reduces the number of recursive calls drastically. For example, in the Fibonacci function, base cases return known values directly. Then, results for fib(2), fib(3), and fib(4) are computed and saved. Later calls reuse these saved results instead of recalculating. This makes recursion efficient and fast.

Practice

(1/5)
1. What is the main purpose of using memoization in recursive functions?
easy
A. To store results of expensive function calls and reuse them
B. To make the code shorter and simpler
C. To avoid using loops in recursion
D. To increase the number of recursive calls

Solution

  1. Step 1: Understand recursion inefficiency

    Recursive functions often repeat the same calculations multiple times, which wastes time.
  2. Step 2: Role of memoization

    Memoization saves the results of these repeated calculations so they can be reused instead of recalculated.
  3. Final Answer:

    To store results of expensive function calls and reuse them -> Option A
  4. Quick Check:

    Memoization = Store and reuse results [OK]
Hint: Memoization saves repeated results to speed recursion [OK]
Common Mistakes:
  • Thinking memoization makes code shorter
  • Confusing memoization with iteration
  • Believing memoization increases recursion calls
2. Which of the following Java code snippets correctly declares a memoization cache for storing integer results by input integer keys?
easy
A. Map memo = new HashMap<>();
B. List<Integer> memo = new ArrayList<>();
C. int[] memo = new int();
D. HashSet<Integer> memo = new HashSet<>();

Solution

  1. Step 1: Identify suitable data structure for key-value pairs

    Memoization requires storing results by input keys, so a Map is ideal.
  2. Step 2: Check Java syntax correctness

    Map memo = new HashMap<>(); uses Map with HashMap, which is correct syntax for memoization cache.
  3. Final Answer:

    Map memo = new HashMap<>(); -> Option A
  4. Quick Check:

    Memo cache = Map for key-value pairs [OK]
Hint: Use Map for key-value memo cache in Java [OK]
Common Mistakes:
  • Using List instead of Map for memoization
  • Incorrect array declaration syntax
  • Using Set which stores only keys, no values
3. What will be the output of the following Java code using memoization for Fibonacci numbers?
import java.util.*;
public class FibMemo {
  static Map memo = new HashMap<>();
  public static int fib(int n) {
    if (n <= 1) return n;
    if (memo.containsKey(n)) return memo.get(n);
    int result = fib(n-1) + fib(n-2);
    memo.put(n, result);
    return result;
  }
  public static void main(String[] args) {
    System.out.println(fib(5));
  }
}
medium
A. Error at runtime
B. 8
C. 5
D. 13

Solution

  1. Step 1: Understand Fibonacci sequence calculation

    fib(5) = fib(4) + fib(3), and so on, with base cases fib(0)=0, fib(1)=1.
  2. Step 2: Calculate fib(5) with memoization

    fib(2)=1, fib(3)=2, fib(4)=3, fib(5)=5. Memoization avoids repeated calls but result is same.
  3. Final Answer:

    5 -> Option C
  4. Quick Check:

    fib(5) = 5 [OK]
Hint: Recall Fibonacci(5) = 5, memoization doesn't change result [OK]
Common Mistakes:
  • Confusing Fibonacci values for wrong n
  • Assuming memoization changes output
  • Thinking code causes runtime error
4. Identify the error in this Java memoized factorial function:
import java.util.*;
public class FactorialMemo {
  static Map memo = new HashMap<>();
  public static int fact(int n) {
    if (n == 0) return 1;
    if (memo.containsKey(n)) return memo.get(n);
    int result = n * fact(n - 1);
    memo.put(n, result);
    return result;
  }
  public static void main(String[] args) {
    System.out.println(fact(-1));
  }
}
medium
A. Memo map is not initialized properly
B. fact method should return long instead of int
C. Incorrect multiplication order in recursion
D. No base case for negative input causes infinite recursion

Solution

  1. Step 1: Analyze base cases and input handling

    Base case handles n == 0 only, but negative n causes no stop condition.
  2. Step 2: Effect of negative input

    Calling fact(-1) leads to infinite recursion because n never reaches 0 or memoized value.
  3. Final Answer:

    No base case for negative input causes infinite recursion -> Option D
  4. Quick Check:

    Missing negative base case = infinite recursion [OK]
Hint: Check base cases cover all input ranges [OK]
Common Mistakes:
  • Ignoring negative input handling
  • Assuming memo initialization error
  • Thinking multiplication order causes error
5. You want to optimize a recursive function that calculates the number of ways to climb n stairs taking 1 or 2 steps at a time. Which memoization approach below correctly implements this in Java?
hard
A. Use a List<Integer> to store results; always calculate recursively without checking cache.
B. Use a Map to store results; check cache before recursive calls; store results after calculation.
C. Use an int array without initializing values; store results only after all recursion ends.
D. Use a Set<Integer> to store visited stairs; return size of set as result.

Solution

  1. Step 1: Understand problem and memoization needs

    We must store number of ways for each stair number to avoid repeated calculations.
  2. Step 2: Evaluate memoization approaches

    Use a Map to store results; check cache before recursive calls; store results after calculation. uses Map to store and check results before recursion, which is correct memoization practice.
  3. Final Answer:

    Use a Map to store results; check cache before recursive calls; store results after calculation. -> Option B
  4. Quick Check:

    Memo = Map with cache check and store [OK]
Hint: Check cache before recursion, store after calculation [OK]
Common Mistakes:
  • Not checking cache before recursive calls
  • Using List or Set incorrectly for memoization
  • Storing results too late or not at all
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard