🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

Hard Coding Patterns: Dynamic Programming and Search

Python InterviewCoding Challenges⭐ Premium
Python Interview · Difficulty: Hard

Hard problems have a method, not a trick

Dynamic programming and backtracking intimidate candidates because the finished solutions look like magic. They are not. Every DP solution comes from the same three questions — what is the state, what recurrence connects states, and where do the base cases sit — and every backtracking solution comes from the same template — choose, recurse, undo, with pruning to cut impossible branches early. The hard part in an interview is not typing the code; it is arriving at the state definition and proving the recurrence out loud before you write anything. This lesson gives you a repeatable process for both families, worked through the classic problems that keep appearing in onsites.

Prerequisites

  • !Recursion, memoization, and basic complexity analysis
  • !The easy and medium coding pattern lessons

What You'll Learn

  • 1Derive a DP state and recurrence from a problem statement, top-down and bottom-up
  • 2Implement coin change, LCS, edit distance, and knapsack without copying formulas blindly
  • 3Apply the backtracking template to subsets, permutations, combination sums, and N-Queens
  • 4Recognize pruning opportunities that turn exponential searches into practical ones

The DP process: state, recurrence, base

Start top-down. Define a function over the smallest interesting input — min_coins(amount), lcs(i, j) — and ask what the answer depends on. That dependency graph is your recurrence. Memoize the function with a dict or functools.lru_cache, and you have a correct, if occasionally slow, solution. Then, if the interview asks for space improvements or bottom-up form, fill a table in dependency order and notice that many 2D recurrences only need the previous row, collapsing space from O(mn) to O(n).

Coin change is the gateway problem: the minimum coins for an amount is one plus the best result for the amount minus each coin, with zero as the base case and infinity sentinel for unreachable amounts. Longest common subsequence carries two indices; matching characters extend a diagonal, mismatches take the better of skipping a character from either string. Edit distance adds a third branch for substitution. The 0/1 knapsack recurrence decides for each item whether including it improves the best value at each capacity. Learn to narrate each recurrence in one sentence — "for this item and this capacity, either skip it or take it and pay its weight" — because the narration is what the interviewer grades.

python
from functools import lru_cache


def coin_change(coins, amount):
    """Bottom-up minimum coins; O(amount * len(coins)) time."""

    @lru_cache(maxsize=None)
    def best(remaining):
        if remaining == 0:
            return 0
        result = float("inf")
        for coin in coins:
            if coin <= remaining:
                result = min(result, 1 + best(remaining - coin))
        return result

    answer = best(amount)
    return answer if answer != float("inf") else -1


def edit_distance(a, b):
    """Levenshtein distance with a full table; O(m * n)."""
    m, n = len(a), len(b)
    dp = [[0] * (n + 1) for _ in range(m + 1)]
    for i in range(m + 1):
        dp[i][0] = i
    for j in range(n + 1):
        dp[0][j] = j
    for i in range(1, m + 1):
        for j in range(1, n + 1):
            if a[i - 1] == b[j - 1]:
                dp[i][j] = dp[i - 1][j - 1]
            else:
                dp[i][j] = 1 + min(
                    dp[i - 1][j],      # delete from a
                    dp[i][j - 1],      # insert into a
                    dp[i - 1][j - 1],  # replace
                )
    return dp[m][n]


print(coin_change((1, 5, 10, 25), 30))  # 2
print(edit_distance("horse", "ros"))    # 3

Knapsack variants and space optimization

The 0/1 knapsack table is items by capacity; each cell is the best value considering the first i items under a capacity limit. The unbounded variant allows reuse, so the inner loop over capacity runs forward instead of backward, letting an item be taken multiple times. Subset-sum is the boolean cousin: reachable capacities form a bitset of trues, updated per item from high capacity downward so each item is used once. Target-sum converts to subset-sum by noting that choosing plus or minus signs partitions the numbers into two groups whose difference is the target.

The space optimization interviewers want to see: a 1D capacity array updated in the right direction. For 0/1 knapsack, iterate capacity downward so the previous row's values remain available; for unbounded, iterate upward so the current item can compound. Stating that direction rule confidently separates candidates who understand the table from candidates who memorized it.

python
def knapsack_01(weights, values, capacity):
    """1D-optimized 0/1 knapsack; O(n * capacity) time."""
    best = [0] * (capacity + 1)
    for weight, value in zip(weights, values):
        for w in range(capacity, weight - 1, -1):
            best[w] = max(best[w], best[w - weight] + value)
    return best[capacity]


def subset_sum(nums, target):
    """True if any subset sums to target."""
    reachable = [False] * (target + 1)
    reachable[0] = True
    for num in nums:
        for t in range(target, num - 1, -1):
            reachable[t] = reachable[t] or reachable[t - num]
    return reachable[target]


print(knapsack_01((1, 3, 4, 5), (1, 4, 5, 7), 7))  # 9
print(subset_sum((3, 34, 4, 12, 5, 2), 9))         # True

Backtracking: choose, recurse, undo

The backtracking template has four parts: a base case that records a complete solution, a loop over choices, a guarded recursive step that makes the choice, and an undo that restores state after the recursion returns. Subsets append a copy of the current path at every node of the recursion tree. Permutations track a used-boolean array. Combination sum restarts the candidate index (allowing repeats) or advances it (disallowing repeats) — that single index argument encodes the repetition rule, which is worth pointing out explicitly.

N-Queens shows the pruning half of the discipline. Placing a queen on a row requires checking the column and both diagonals against previously placed queens; the check is O(n) per candidate, but the pruning cuts the brute-force n^n search down to something feasible. Sudoku solving is the same skeleton with a board mutated in place and restored on failure. When an interviewer watches you solve a new backtracking problem, they want to see the template appear immediately and the pruning constraints named before optimization talk begins.

python
def subsets(nums):
    """All subsets via choose/undo; O(2^n * n)."""
    result = []

    def backtrack(start, path):
        result.append(path[:])
        for i in range(start, len(nums)):
            path.append(nums[i])
            backtrack(i + 1, path)
            path.pop()

    backtrack(0, [])
    return result


def combination_sum(candidates, target):
    """Combinations summing to target; repeats allowed."""
    result, ordered = [], sorted(candidates)

    def backtrack(start, path, remaining):
        if remaining == 0:
            result.append(path[:])
            return
        for i in range(start, len(ordered)):
            value = ordered[i]
            if value > remaining:
                break  # sorted input: no later candidate can fit
            path.append(value)
            backtrack(i, path, remaining - value)
            path.pop()

    backtrack(0, [], target)
    return result


print(len(subsets([1, 2, 3])))            # 8
print(combination_sum((2, 3, 6, 7), 7))  # [[2, 2, 3], [7]]

Advanced patterns: LIS, interval DP, and games

Longest increasing subsequence has an O(n log n) patience-sorting solution: maintain a tails list where tails[k] is the smallest possible tail of an increasing subsequence of length k+1; binary-search each element's insertion point. Max-product subarray tracks both maximum and minimum products because a negative number flips their roles. Interval DP — burst balloons, stone game — iterates over interval lengths, choosing a split point or a first move and combining results from smaller intervals; the loop order over lengths is what guarantees subproblems are solved before use.

Game DP deserves a special note: define dp[i][j] as the best score difference the current player can achieve over the opponent on the interval, recursing on the opponent's optimal reply. The sign-flipping recurrence is the same one that appears in minimax search. If the interviewer pushes further, mention state compression with bitmasks for small n and the fact that top-down memoized forms are usually safer to write under time pressure than bottom-up tables.

FamilyState sketchRecurrence shapeTypical complexity
Linear DPbest ending at itake vs skipO(n)
Grid / LCS-styledp[i][j] on two prefixesdiagonal or max of two neighborsO(mn)
Knapsackitem index and capacityinclude or excludeO(nC)
Interval DPdp[left][right] over rangessplit or pick an endpointO(n³)
Backtrackingpath and start indexchoose, recurse, undoexponential with pruning

Presenting a hard solution under time pressure

Structure the conversation. Restate the problem and clarify constraints — n up to 10³ suggests O(n²), up to 10⁵ suggests O(n log n) or linear, small n allows exponential search with pruning. Propose the brute force and its complexity. Name the pattern. Derive the state and recurrence before touching code. Write the top-down memoized version first; it is shorter and harder to index incorrectly. Test with the smallest non-trivial input, then discuss space optimization or bottom-up conversion if asked. Candidates who follow this arc rarely look lost, even when the problem is new to them, because every step has a purpose the interviewer can evaluate.

Common Mistakes

Writing a bottom-up table before agreeing on the state definition

Fix: Derive and state the recurrence in plain English first; then encode it either way

Iterating the 0/1 knapsack capacity loop in the wrong direction

Fix: Downward for 0/1 (each item once), upward for unbounded (reuse allowed)

Forgetting to copy the path before appending it to the result

Fix: result.append(path[:]) — the copy is what keeps snapshots independent

Skipping pruning because the template works without it

Fix: Sort candidates and break early; prune with bounds before recursing

Best Practices

  • State constraints first; they tell you the complexity you are allowed
  • Write the memoized recursion before the table — correctness first, then optimization
  • Name the backtracking template out loud so structure emerges before details
  • Test with tiny inputs, including the empty case, before claiming the solution works

Interview Questions

Q1: Top-down versus bottom-up dynamic programming?

Top-down memoization mirrors the recurrence and only computes reachable states; it is easier to write correctly. Bottom-up fills tables in dependency order, enabling space optimization like rolling arrays, at the cost of index gymnastics.

Q2: How do you optimize DP space?

Identify which previous states the current state reads. If only the prior row matters, keep two rows or one updated in the right direction; if only a window matters, keep a deque or ring buffer of that window.

Q3: When is memoization better than tabulation?

Under interview time pressure and when state spaces are sparse. Tabulation wins when you need maximal cache locality, iterative execution, or trivial space optimization.

Q4: How do you handle DP with multiple constraints?

Add an index per dimension, even if that grows the table; then look for reductions — two constraints often collapse to one difference or sum. State the resulting complexity honestly.

Q5: What is state compression in DP?

Encoding a DP state — often a subset of items — into a bitmask or into a smaller array, reducing memory from exponential in n to polynomial or from O(n²) to O(n). The knapsack 1D array is the everyday example.

Key Takeaways

  • DP is a process — state, recurrence, base cases — not a bag of tricks
  • Start top-down with lru_cache; optimize to tables only when asked
  • Knapsack direction rules and LIS's tails array are high-frequency knowledge
  • Backtracking is choose, recurse, undo; pruning is what makes it feasible
  • Interval and game DP iterate over lengths and combine smaller intervals
  • Present constraints, brute force, pattern, then code — structure impresses under pressure
🔒

Premium Content

Hard Coding Patterns: Dynamic Programming and Search

You've previewed the first section. Unlock this full lesson and 900+ advanced tutorials with a Premium plan.

🎯End-to-end Projects
💼Interview Prep
📜Certificates
🤝Community Access

Already a member? Log in

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Advertisement