SteelReed

Search

Search posts, questions…

2. Data Structures & Algorithms

Interview practice: graphs and dynamic programming in Java

Patterns for graph and dynamic programming interview problems: adjacency lists, BFS/DFS on grids, topological sort, BFS and Dijkstra for shortest paths, union-find; defining DP state through coin change, LIS, LCS, 0/1 knapsack and edit distance; with a table mapping problem signals to techniques and the common traps.

18 Nov 20267 min readMid

–

1. The problem

"Fewest coins" with denominations {1, 3, 4} and amount 6: the AI's greedy solution gives 3 coins (4 + 1 + 1); the right answer is 2 (3 + 3), and it passed every sample test because the samples used {1, 5, 10}. In the same session, BFS on a 1000×1000 grid took 40 seconds because cells were enqueued many times.

2. Key idea

Recognize the signal in the problem first, then choose the technique. For DP the routine is: define dp[...] in one sentence → recurrence → base case → fill order. Top-down memoization is easy to write; bottom-up tables can't overflow the stack and often shrink memory.

Problem State Recurrence
Coin change dp[a]: fewest coins making a min(dp[a - c] + 1)
LIS dp[i]: longest increasing run ending at i max(dp[j] + 1) with nums[j] < nums[i]
LCS dp[i][j]: LCS of a[0..i), b[0..j) match: diagonal + 1; else max of two cells
0/1 knapsack dp[c]: best value with capacity c max(dp[c], dp[c - w] + v), c descending
Edit distance dp[i][j]: edits turning a[0..i) into b[0..j) match: diagonal; else 1 + min of three cells
Technique Use when Don't use when
BFS shortest by edge count edges have different weights
Dijkstra non-negative weights negative edges (use Bellman-Ford)
Recursive DFS small regions, cycle detection large grids: depth equals cell count, stack overflow
Greedy there's a proof (non-overlapping intervals, canonical coins) no counterexample has been ruled out

3. In Java

JAVA
static int coinChange(int[] coins, int amount) {      // {1,3,4}, 6 -> 2
    int[] dp = new int[amount + 1];
    Arrays.fill(dp, amount + 1);                      // "infinity" that doesn't overflow on +1
    dp[0] = 0;
    for (int a = 1; a <= amount; a++)
        for (int c : coins)
            if (c <= a) dp[a] = Math.min(dp[a], dp[a - c] + 1);
    return dp[amount] > amount ? -1 : dp[amount];
}
 
// Dijkstra: PriorityQueue can't "decrease key", so push a new entry and skip stale ones on poll
PriorityQueue<int[]> pq = new PriorityQueue<>(Comparator.comparingInt(x -> x[1]));
pq.offer(new int[]{src, 0});
while (!pq.isEmpty()) {
    int[] cur = pq.poll();
    if (cur[1] > dist[cur[0]]) continue;              // stale entry
    for (int[] e : adj.get(cur[0]))
        if (cur[1] + e[1] < dist[e[0]]) { dist[e[0]] = cur[1] + e[1]; pq.offer(new int[]{e[0], dist[e[0]]}); }
}

Complexity: coin change O(amount · k); Dijkstra O(E log V). Other languages: Python has heapq and collections.deque; Go has container/heap.

Topological sort, union-find and knapsack
  • Kahn: count each node's in-degree, enqueue nodes with in-degree 0, pop them and decrement their targets' in-degrees. Fewer than n nodes popped means a cycle.
  • Union-find: each group is a tree with a representative root; find with path compression and union by rank make each operation nearly O(1). The first edge whose ends are already in one group closes a cycle.
  • 0/1 knapsack with a 1D array: iterate capacity downward (for c = W down to w) so each item is used once. Iterating upward turns it into unbounded knapsack.
  • LIS in O(n log n): keep a tails array and binary search the replacement position.

4. Working with AI

Hand to AI: random tests comparing a solution with brute force, converting recursive DFS to BFS, drawing a DP table for a small input.

Check yourself in AI-written code:

  • Greedy solutions come with a proof or a counterexample check.
  • BFS marks visited on enqueue, not on dequeue.
  • Dijkstra skips stale entries and isn't used with negative edges.
  • dp[...] has a one-sentence definition; "infinity" doesn't overflow when added to.
  • Large grids don't use recursive DFS.

5. Exercises

Exercise 1: Review a grid BFS

The AI wrote a shortest-path BFS and says "O(R·C)". On a 1000×1000 grid with many open cells, it's very slow and memory-hungry. Find the bug and fix it.

JAVA
while (!queue.isEmpty()) {
    int[] cur = queue.poll();
    if (visited[cur[0]][cur[1]]) continue;
    visited[cur[0]][cur[1]] = true;
    for (int[] d : DIRS) {
        int r = cur[0] + d[0], c = cur[1] + d[1];
        if (inside(r, c) && grid[r][c] == 0 && !visited[r][c]) queue.offer(new int[]{r, c, cur[2] + 1});
    }
}
Solution 1

Marking visited on dequeue lets every neighbor enqueue a cell before it's dequeued: up to 4 copies (8 with 8 directions). The queue balloons several times over, and memory and time grow with it.

Fix: mark it as soon as it's enqueued.

JAVA
if (inside(r, c) && grid[r][c] == 0 && !visited[r][c]) {
    visited[r][c] = true;
    queue.offer(new int[]{r, c, cur[2] + 1});
}

Mark the start cell before enqueuing it too. Both versions return the right answer; only the cost differs.

Exercise 2: A 0/1 knapsack broken by loop direction

The AI wrote for (item) for (c = w; c <= W; c++) dp[c] = max(dp[c], dp[c - w] + v) for "each item at most once", with W = 10 and a single item of weight 3, value 5. The result is 15. Explain and fix.

Solution 2

Iterating c upward means dp[c - w] was already updated by this same item: dp[3] = 5, dp[6] = dp[3] + 5 = 10, dp[9] = 15. The item is taken three times: that's unbounded knapsack.

Fix: for (c = W; c >= w; c--). Then dp[c - w] still holds the value before this item, so each item is used at most once; the result is 5.

Summary

  • Recognize the signal: grid, shortest, weights, dependencies, groups, counting or min/max.
  • BFS for edge counts, Dijkstra for non-negative weights, skipping stale heap entries.
  • BFS marks visited on enqueue.
  • DP: define dp[...] in words first; greedy needs a proof.
  • 0/1 knapsack on a 1D array: capacity descending.

Further reading: Trees and heaps.


Self-compiled notes from official documentation and hands-on practice.

Practice interview questions on this topic

All Collections & DSA questions →

Loading comments…
Next on the roadmapJava generics: type safety, wildcards, PECS and type erasure