Skip to main content
PreparationZone Logo
PreparationZone
Back to Fundamentals

Fundamentals · Medium · Free

Fibonacci with recursion, memoization, and bottom-up DP.

FresherFundamentalsData Structures & Algorithms
Model answer

Fibonacci DP

java
int fib(int n) {
  if (n <= 1) return n;
  int a = 0, b = 1;
  for (int i = 2; i <= n; i++) {
    int c = a + b;
    a = b; b = c;
  }
  return b;
}
  • Naive recursion O(2^n)
  • Memoization O(n)
  • Bottom-up O(n) time O(1) space
Template for DP: define state, recurrence, base cases.