Bird
Raised Fist0
DSA Rustprogramming~20 mins

Fibonacci Using DP in DSA Rust - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Fibonacci DP Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of Fibonacci DP with memoization
What is the output of this Rust code that calculates the 7th Fibonacci number using memoization?
DSA Rust
fn fib(n: usize, memo: &mut Vec<Option<u64>>) -> u64 {
    if let Some(val) = memo[n] {
        return val;
    }
    if n <= 1 {
        memo[n] = Some(n as u64);
        return n as u64;
    }
    let result = fib(n - 1, memo) + fib(n - 2, memo);
    memo[n] = Some(result);
    result
}

fn main() {
    let n = 7;
    let mut memo = vec![None; n + 1];
    let result = fib(n, &mut memo);
    println!("{}", result);
}
A21
B13
C8
D34
Attempts:
2 left
💡 Hint
Remember that Fibonacci sequence starts with 0, 1, 1, 2, 3, 5, 8, 13...
❓ Predict Output
intermediate
2:00remaining
Output of bottom-up Fibonacci DP
What is the output of this Rust code that calculates the 10th Fibonacci number using bottom-up dynamic programming?
DSA Rust
fn fib(n: usize) -> u64 {
    let mut dp = vec![0u64; n + 1];
    dp[0] = 0;
    if n > 0 {
        dp[1] = 1;
    }
    for i in 2..=n {
        dp[i] = dp[i - 1] + dp[i - 2];
    }
    dp[n]
}

fn main() {
    let result = fib(10);
    println!("{}", result);
}
A55
B89
C34
D144
Attempts:
2 left
💡 Hint
The 10th Fibonacci number (0-based) is 55.
🔧 Debug
advanced
2:00remaining
Identify the error in this Fibonacci DP code
What error does this Rust code produce when calculating the 5th Fibonacci number using memoization?
DSA Rust
fn fib(n: usize, memo: &mut Vec<Option<u64>>) -> u64 {
    if memo[n].is_some() {
        return memo[n].unwrap();
    }
    if n <= 1 {
        return n as u64;
    }
    let result = fib(n - 1, memo) + fib(n - 2, memo);
    memo[n] = Some(result);
    result
}

fn main() {
    let n = 5;
    let mut memo = vec![None; n + 1];
    let result = fib(n, &mut memo);
    println!("{}", result);
}
AIndex out of bounds panic
BCompilation error due to missing return
CInfinite recursion causing stack overflow
DCorrect output 5
Attempts:
2 left
💡 Hint
Check the size of the memo vector compared to the index n.
🧠 Conceptual
advanced
1:30remaining
Why use dynamic programming for Fibonacci?
Which reason best explains why dynamic programming improves Fibonacci number calculation compared to naive recursion?
AIt uses less memory by not storing any results
BIt converts Fibonacci into a sorting problem
CIt uses randomization to guess the next number
DIt avoids repeated calculations by storing intermediate results
Attempts:
2 left
💡 Hint
Think about what happens when naive recursion calls the same function multiple times with the same input.
🚀 Application
expert
2:30remaining
Calculate sum of first N Fibonacci numbers using DP
Given the Rust function below that calculates Fibonacci numbers using DP, which option correctly prints the sum of the first 8 Fibonacci numbers (0-based)?
DSA Rust
fn fib(n: usize) -> u64 {
    let mut dp = vec![0u64; n + 1];
    dp[0] = 0;
    if n > 0 {
        dp[1] = 1;
    }
    for i in 2..=n {
        dp[i] = dp[i - 1] + dp[i - 2];
    }
    dp[n]
}

fn main() {
    let n = 8;
    // Calculate sum of first n Fibonacci numbers here
    // Fill in the blank
}
Alet sum: u64 = (0..n).map(|i| fib(i)).sum(); println!("{}", sum);
Blet sum: u64 = (1..=n).map(|i| fib(i)).sum(); println!("{}", sum);
Clet sum: u64 = (0..=n).map(|i| fib(i)).sum(); println!("{}", sum);
Dlet sum: u64 = (1..n).map(|i| fib(i)).sum(); println!("{}", sum);
Attempts:
2 left
💡 Hint
Sum includes Fibonacci numbers from index 0 to 8 inclusive.

Practice

(1/5)
1. What is the main advantage of using dynamic programming (DP) to calculate Fibonacci numbers compared to a simple recursive approach?
easy
A. It avoids repeated calculations by storing intermediate results.
B. It uses less memory by not storing any results.
C. It calculates Fibonacci numbers using only recursion without loops.
D. It always runs in constant time regardless of input size.

Solution

  1. Step 1: Understand recursive Fibonacci inefficiency

    Simple recursion recalculates the same Fibonacci values many times, causing exponential time complexity.
  2. Step 2: How DP improves calculation

    DP stores intermediate Fibonacci values in a table (memoization or tabulation), so each value is computed once.
  3. Final Answer:

    It avoids repeated calculations by storing intermediate results. -> Option A
  4. Quick Check:

    DP stores results to avoid repeats [OK]
Hint: DP saves previous results to speed up Fibonacci [OK]
Common Mistakes:
  • Thinking DP uses no extra memory
  • Believing DP always runs in constant time
  • Confusing recursion with DP
2. Which of the following Rust code snippets correctly initializes a vector to store Fibonacci numbers for dynamic programming?
easy
A. let fib = vec![0; n];
B. let mut fib = vec![0; n+1];
C. let mut fib = Vec::new();
D. let fib = [0; n+1];

Solution

  1. Step 1: Check vector size for DP storage

    We need a vector of size n+1 to store Fibonacci numbers from 0 to n.
  2. Step 2: Verify mutability and initialization

    Vector must be mutable to update values; initialized with zeros for all positions.
  3. Final Answer:

    let mut fib = vec![0; n+1]; -> Option B
  4. Quick Check:

    Mutable vector with n+1 zeros [OK]
Hint: Use mutable vector with size n+1 for DP array [OK]
Common Mistakes:
  • Using immutable vector when updates needed
  • Incorrect vector size causing index errors
  • Using fixed-size array without mutability
3. What will be the output of the following Rust code that uses bottom-up DP to compute Fibonacci numbers?
fn fib(n: usize) -> usize {
    let mut dp = vec![0; n+1];
    dp[1] = 1;
    for i in 2..=n {
        dp[i] = dp[i-1] + dp[i-2];
    }
    dp[n]
}

fn main() {
    println!("{}", fib(5));
}
medium
A. 13
B. 8
C. 5
D. 3

Solution

  1. Step 1: Trace DP array filling for n=5

    dp[0]=0, dp[1]=1; then dp[2]=1, dp[3]=2, dp[4]=3, dp[5]=5.
  2. Step 2: Return dp[5]

    Function returns dp[5], which is 5.
  3. Final Answer:

    5 -> Option C
  4. Quick Check:

    Fibonacci(5) = 5 [OK]
Hint: Bottom-up DP sums previous two values [OK]
Common Mistakes:
  • Confusing index starting points
  • Off-by-one errors in loop range
  • Misreading dp array values
4. Identify the error in this Rust code for Fibonacci using DP and select the correct fix:
fn fib(n: usize) -> usize {
    let mut dp = vec![0; n];
    dp[0] = 0;
    dp[1] = 1;
    for i in 2..=n {
        dp[i] = dp[i-1] + dp[i-2];
    }
    dp[n]
}
medium
A. Change vector size to n+1 and return dp[n]
B. Change vector size to n and return dp[n-1]
C. Initialize dp with zeros and ones alternatively
D. Remove dp[0] assignment since it's zero by default

Solution

  1. Step 1: Check vector size and indexing

    Vector size is n (indices 0 to n-1), but loop 2..=n and dp[n] access index n, causing out of bounds panic.
  2. Step 2: Fix vector size

    Change to vec![0; n+1] to store values up to index n.
  3. Final Answer:

    Change vector size to n+1 and return dp[n] -> Option A
  4. Quick Check:

    Size n+1 for indices 0 to n [OK]
Hint: Vector of size n+1 stores fib[0..n] [OK]
Common Mistakes:
  • Accessing dp[n] causing panic
  • Incorrect vector size for indexing
  • Ignoring zero-based indexing
5. You want to compute the 10th Fibonacci number using top-down DP (memoization) in Rust. Which code snippet correctly implements memoization to avoid repeated calculations?
fn fib_memo(n: usize, memo: &mut Vec) -> usize {
    if n <= 1 {
        return n;
    }
    if let Some(val) = memo[n] {
        return val;
    }
    let result = fib_memo(n-1, memo) + fib_memo(n-2, memo);
    memo[n] = Some(result);
    result
}

fn main() {
    let n = 10;
    let mut memo = vec![None; n+1];
    println!("{}", fib_memo(n, &mut memo));
}
hard
A. Incorrect because base case should return 0 for n=1
B. Incorrect because memo vector should store usize, not Option<usize>
C. Incorrect because memo is not passed as mutable reference
D. Correct implementation of top-down DP with memoization

Solution

  1. Step 1: Check memo vector type and initialization

    Memo uses Option<usize> to track computed values; initialized with None for all indices.
  2. Step 2: Verify memoization logic

    Function returns stored value if present; otherwise computes recursively and stores result.
  3. Step 3: Confirm base case correctness

    Returns n for n=0 or 1, which matches Fibonacci definition.
  4. Final Answer:

    Correct implementation of top-down DP with memoization -> Option D
  5. Quick Check:

    Memo stores Option, uses recursion with caching [OK]
Hint: Use Option to track computed Fibonacci values [OK]
Common Mistakes:
  • Using usize vector without Option causes wrong caching
  • Wrong base case returns
  • Not passing memo as mutable reference
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