LearnFrenzy
Sign in Take a free test

Data Structures interview · Set 7 of 14

Dynamic Programming

  • 5 follow-up questions
  • 4 key points
  • Code examples
Test yourself

State, choice, recurrence, base case

DP is careful recursion with memory. Interviewers reward the process: brute force first, spot repeated work, cache it, then optimise space. Practise a handful of classic patterns and new problems start to look familiar.

  • 1-D DPStairs, house robber, coin change.
  • 2-D DPLCS, edit distance, grid paths.
  • OptimisationRolling arrays and binary-search tricks.

Dynamic programming has a reputation for being hard, but every DP solution answers the same four questions: what is the state, what is the choice at each step, what is the recurrence, and what are the base cases? Answer those out loud and the code almost writes itself.

1. When does a problem need dynamic programming?

When it has optimal substructure (the best answer is built from best answers to smaller problems) and overlapping subproblems (the same smaller problems repeat). Signal words: “number of ways”, “minimum cost”, “maximum profit”, “longest”, “can you reach”.


2. Memoisation vs tabulation — what is the difference?

Memoisation is top-down: write the natural recursion and cache results. Tabulation is bottom-up: fill a table from the base cases upward with loops. Tabulation avoids recursion depth limits and often allows space optimisation; memoisation is quicker to write and only computes states you actually need.


3. Climbing stairs: how many ways to reach step n taking 1 or 2 steps?

To reach step i you came from i−1 or i−2, so ways[i] = ways[i−1] + ways[i−2]. Only the last two values matter, so space is O(1).

int climb(int n) {
    int a = 1, b = 1;             // ways to reach step 0 and step 1
    for (int i = 2; i <= n; i++) { int c = a + b; a = b; b = c; }
    return b;
}

4. Coin change: the fewest coins to make an amount.

State: dp[x] = fewest coins for amount x. Choice: the last coin used. Recurrence: dp[x] = 1 + min(dp[x − coin]). Greedy fails for coins like {1, 3, 4} and amount 6 (greedy gives 3 coins, the answer is 2).

int coinChange(int[] coins, int amount) {
    int[] dp = new int[amount + 1];
    Arrays.fill(dp, amount + 1);           // "infinity"
    dp[0] = 0;
    for (int x = 1; x <= amount; x++)
        for (int c : coins)
            if (c <= x) dp[x] = Math.min(dp[x], dp[x - c] + 1);
    return dp[amount] > amount ? -1 : dp[amount];
}

5. Longest common subsequence of two strings.

State: dp[i][j] = LCS of the first i characters of a and first j of b. If the characters match, extend the diagonal; otherwise take the better of skipping one character from either string. O(n·m). It underlies diff tools and DNA comparison.

int lcs(String a, String b) {
    int[][] dp = new int[a.length() + 1][b.length() + 1];
    for (int i = 1; i <= a.length(); i++)
        for (int j = 1; j <= b.length(); j++)
            dp[i][j] = a.charAt(i - 1) == b.charAt(j - 1)
                ? dp[i - 1][j - 1] + 1
                : Math.max(dp[i - 1][j], dp[i][j - 1]);
    return dp[a.length()][b.length()];
}

6. 0/1 knapsack: maximum value within a weight limit.

For each item, either skip it or take it (if it fits). With a 1-D array, loop capacity backwards so each item is used at most once.

int knapsack(int[] wt, int[] val, int cap) {
    int[] dp = new int[cap + 1];
    for (int i = 0; i < wt.length; i++)
        for (int w = cap; w >= wt[i]; w--)          // backwards: 0/1, not unlimited
            dp[w] = Math.max(dp[w], dp[w - wt[i]] + val[i]);
    return dp[cap];
}

7. Longest increasing subsequence — O(n²) and O(n log n).

Simple DP: dp[i] = LIS ending at i, checking all earlier smaller elements — O(n²). Faster: keep an array of the smallest possible tail for each length and place each number with binary search — O(n log n).

int lis(int[] nums) {
    List<Integer> tails = new ArrayList<>();
    for (int x : nums) {
        int i = Collections.binarySearch(tails, x);
        if (i < 0) i = -(i + 1);
        if (i == tails.size()) tails.add(x); else tails.set(i, x);
    }
    return tails.size();
}

8. How do you approach a DP problem you have never seen?

1) Write the brute-force recursion. 2) Identify the parameters that change — that is your state. 3) Add a cache. 4) If needed, convert to a table and reduce space. Explaining these steps calmly is often worth more than jumping to the final table.


Remember

Key points

  • Two conditions

    Optimal substructure and overlapping subproblems.

  • Greedy can fail

    Coin change {1,3,4} for 6 proves it.

  • Loop direction matters

    Backwards for 0/1 knapsack, forwards for unlimited.

  • Reduce space

    Keep only the rows or values you still need.

Interview drill

Follow-up questions

What the interviewer asks after your first answer. Turn on practice mode, answer each one aloud, then reveal.

  1. 1 How do you compute the edit distance between two words? Intermediate

    dp[i][j] = edits to turn the first i chars into the first j. If characters match, copy the diagonal; else 1 + min(insert, delete, replace).

  2. 2 House robber: maximum money without robbing two adjacent houses. Basic

    best[i] = max(best[i−1], best[i−2] + money[i]), kept in two variables.

  3. 3 How many unique paths are there in an m × n grid moving only right or down? Basic

    dp[r][c] = dp[r−1][c] + dp[r][c−1], or directly C(m+n−2, m−1).

  4. 4 What is the difference between DP and divide and conquer? Intermediate

    Both split problems, but divide and conquer subproblems do not overlap (merge sort), so caching gives nothing. DP exists because subproblems repeat.

  5. 5 How would you count ways to make an amount with unlimited coins? Advanced

    Loop coins in the outer loop and amounts forwards in the inner loop: ways[x] += ways[x − coin]. Coins outside avoids counting the same combination in different orders.

    int change(int amount, int[] coins) {
        int[] ways = new int[amount + 1];
        ways[0] = 1;
        for (int c : coins)
            for (int x = c; x <= amount; x++) ways[x] += ways[x - c];
        return ways[amount];
    }

Preparing with friends?

Share this page with your study group or placement batch.

Search LearnFrenzy

Esc

Quick links