Tech Interview RoomStudy guides

Dynamic Programming

Climbing stairs / Fibonacci. Show every approach: recursion, memoisation, tabulation, O(1) space, streams and matrix power.

Beginner · 2 min read · Lesson 1 of 6 in Dynamic Programming

Problem

You can climb 1 or 2 steps at a time. How many distinct ways to reach step n? ways(n) = ways(n-1) + ways(n-2), which is Fibonacci. The best question to show the full DP progression.

Pattern

DP progression: recursion (exponential) → memoisation (top-down) → tabulation (bottom-up) → space optimisation (keep only what the recurrence needs).

Approach 1: Plain recursion (feasible only for tiny n, O(2ⁿ))

java
class StairsRecursive {
    static long ways(int n) { return n <= 1 ? 1 : ways(n - 1) + ways(n - 2); }
}

Approach 2: Memoisation with a HashMap (O(n) time, O(n) space)

java
import java.util.HashMap;
import java.util.Map;

class StairsMemo {
    private static final Map<Integer, Long> memo = new HashMap<>();
    static long ways(int n) {
        if (n <= 1) return 1;
        Long cached = memo.get(n);
        if (cached != null) return cached;                       // computeIfAbsent cannot be used: recursive update
        long result = ways(n - 1) + ways(n - 2);
        memo.put(n, result);
        return result;
    }
}

Approach 3: Tabulation (O(n) time, O(n) space)

java
class StairsTable {
    static long ways(int n) {
        long[] dp = new long[Math.max(2, n + 1)];
        dp[0] = 1; dp[1] = 1;
        for (int i = 2; i <= n; i++) dp[i] = dp[i - 1] + dp[i - 2];
        return dp[n];
    }
}

Approach 4: Two variables (O(n) time, O(1) space) — the usual optimal answer

java
class StairsTwoVars {
    static long ways(int n) {
        long prev = 1, cur = 1;                                  // ways(0), ways(1)
        for (int i = 2; i <= n; i++) { long next = prev + cur; prev = cur; cur = next; }
        return cur;
    }
}

Approach 5: Java 8 Stream.iterate over pairs (functional style, O(n))

java
import java.util.stream.Stream;

class StairsStream {
    static long ways(int n) {
        return Stream.iterate(new long[] {1, 1}, p -> new long[] {p[1], p[0] + p[1]})
            .skip(n).findFirst().orElseThrow()[0];
    }
}

Approach 6: Matrix exponentiation (O(log n))

[[1,1],[1,0]]^n contains Fibonacci numbers; fast exponentiation squares the matrix. Use when n is huge (results modulo a prime).

java
class StairsMatrix {
    static long ways(int n) {
        long[][] result = {{1, 0}, {0, 1}}, base = {{1, 1}, {1, 0}};
        for (int p = n; p > 0; p >>= 1) {
            if ((p & 1) == 1) result = mul(result, base);
            base = mul(base, base);
        }
        return result[0][0];                                     // F(n+1) = ways(n)
    }
    private static long[][] mul(long[][] a, long[][] b) {
        return new long[][] {
            {a[0][0] * b[0][0] + a[0][1] * b[1][0], a[0][0] * b[0][1] + a[0][1] * b[1][1]},
            {a[1][0] * b[0][0] + a[1][1] * b[1][0], a[1][0] * b[0][1] + a[1][1] * b[1][1]}};
    }
}

class StairsDemo {
    public static void main(String[] args) {
        System.out.println(StairsRecursive.ways(10) + " " + StairsMemo.ways(10) + " " + StairsTable.ways(10) + " "
            + StairsTwoVars.ways(10) + " " + StairsStream.ways(10) + " " + StairsMatrix.ways(10));   // 89 x6
        System.out.println(StairsTwoVars.ways(90) + " " + StairsMatrix.ways(90));                   // 4660046610375530309 x2
    }
}

Feasible → optimal

O(2ⁿ) recursion → O(n) memoisation/tabulation with O(n) space → O(n) time, O(1) space → O(log n) matrix power. For interviews, show the O(1)-space loop and mention the O(log n) method.

Follow-up questions interviewers ask

Try answering each one before you open it.

Related (same pattern): house robber (no two adjacent houses).

dp[i] = max(dp[i-1], dp[i-2] + nums[i]): the same two-variable rolling technique, O(n) time, O(1) space. House Robber II (circular street) runs it twice: excluding the first house and excluding the last.

Related (same pattern): min cost climbing stairs and decode ways.

Min cost: dp[i] = cost[i] + min(dp[i-1], dp[i-2]). Decode ways ("12" → "AB" or "L"): dp[i] = (valid single digit ? dp[i-1] : 0) + (valid two digits 10..26 ? dp[i-2] : 0). Both are two-variable Fibonacci-style recurrences.