Your country

Tools that support it use your country for local currency, number formats, units and paper size. Your choice is saved only in this browser.

Type a name or a two-letter code. Use the up and down arrow keys to move through the countries, Enter to choose one and Escape to close.

Coding Interview Patterns Module 25

Dynamic programming: knapsack, grids and strings interview questions

Interview questions on “Dynamic programming: knapsack, grids and strings”: warm-ups, then what each harder question tests and how a good answer starts.

40 questions: 11 warm-ups and 29 with model answers · Levels: Fresher to staff

Warm-up questions

Short questions with short answers, each answered in full.

  1. Fresher to mid

    Why does the one-row 0/1 knapsack loop run the capacity downwards?

    Answered in the lesson 0/1 knapsack: table to one row

  2. Fresher to mid

    Is the O(n·W) knapsack algorithm polynomial?

    Answered in the lesson 0/1 knapsack: table to one row

  3. Fresher

    Why does an odd total rule out an equal partition, and how far must the row of reachable totals go when the total is even?

    Answered in the lesson Subset sums, partitions and target signs

  4. Fresher

    Why does the fewest-coins row start with fewest[0] = 0 while the counting row starts with ways[0] = 1?

    Both describe paying an amount of 0. It takes no coins, so the fewest-coins row stores 0 there, and every other entry is 1 + the entry of a smaller amount, so that 0 is what every one-coin answer is built on. There is exactly one way to pay 0, the empty payment, so the counting row stores 1, and every collection is that empty payment with coins added; with ways[0] = 0 every count would stay 0. The other entries start differently too: the fewest-coins row marks the amounts it has not paid yet as unreachable, while the counting row starts them at 0 ways.

    From the lesson Unbounded knapsack and coin change

  5. Fresher

    Why can the route-counting table be filled row by row, left to right, when moves go right or down, but not when moves may also go left or up?

    With moves right or down, every route into a cell comes from the cell above it or the cell to its left, and both come earlier in row-by-row, left-to-right order, so each entry reads only entries that are already final. The cells and moves form a graph without cycles, and that order is a topological order of it. When moves may also go left or up, a route can come back to a cell, so routes can loop for ever, a cell's answer would depend on itself, and no filling order exists. Such problems ask for something else, usually the fewest moves, which breadth-first search finds.

    From the lesson Grid DP: paths, costs and squares

  6. Fresher to mid

    What is the difference between the longest common subsequence and the longest common substring of two strings, and which one does a line diff need?

    A substring is a contiguous run of characters, while a subsequence keeps the order but may skip characters. For TAMARIND and MANDARIN the longest common substring is ARIN, four letters side by side in both words, while the longest common subsequence has five letters, MARIN or AARIN, picked with gaps. The two tables differ in one rule: for a subsequence, a mismatch takes the better of the cell above and the cell to the left, and the answer is the last cell; for a substring, a mismatch resets the cell to 0, and the answer is the largest cell anywhere. A line diff needs the subsequence, because the lines that both versions keep are usually separated by inserted and deleted lines.

    From the lesson Longest common subsequence and diffs

  7. Fresher to mid

    Which edits does the Levenshtein distance count, and why is it never more than the length of the longer string?

    It counts insertions, deletions and replacements of single characters, each costing 1, and keeping an equal character is free. For the bound, let the strings have lengths n ≤ m. Replace each of the first n characters of the shorter string that differs from the character at the same position in the longer one, then insert the remaining m − n characters: at most n + (m − n) = m edits. The distance is also at least m − n, because every edit changes the length by at most one. Mysore and Mysuru, both of six letters, are 2 edits apart, two replacements, and the distance is 0 only for identical strings.

    From the lesson Edit distance with operations

  8. Fresher to mid

    Why does a string of n characters have 2n − 1 centres for palindromic substrings, and what goes wrong if you expand only around the characters?

    A palindrome of odd length has a middle character, and one of even length has a middle gap between two characters. A string of n characters has n characters and n − 1 gaps between neighbours, so there are 2n − 1 possible middles, and each palindromic substring has exactly one of them. Expanding only around characters finds the odd palindromes and misses every even one: in GG it counts G twice but never GG, two instead of three, and in ABBA it misses BB and ABBA. One loop over c from 0 to 2n − 2, starting with lo = c // 2 and hi = lo + c % 2, covers both kinds: even c starts on a character and odd c on a gap.

    From the lesson Palindromic substrings and subsequences

  9. Fresher to mid

    In the wildcard table, why does a star cell need only the cell to its left and the cell above, instead of trying every place the star could end?

    A star can cover any run of the name that ends at the current character, and trying every start of that run would cost O(n) per cell. The cell above already holds the answer for runs that end one character earlier: it is true when the star, with the mask before it, can cover the name up to the previous character. If the star's run is not empty, dropping its last character leaves such a shorter run, so the cell above is true. If the run is empty, the mask without the star must match the same name, which is the cell to the left. Those two cells cover every possible run, so each cell costs O(1) and the whole table O(nm).

    From the lesson Wildcard and regex-style matching

  10. Fresher to mid

    Why must an interleaving check compare len(a) + len(b) with len(c) before it fills its table?

    Because the table only compares letters. Cell (i, j) asks whether a[:i] and b[:j] merge into c[:i + j], so the answer cell (n, m) looks at c[:n + m] and nothing beyond it. If c is longer, its extra letters at the end are never read, and a broadcast with additions would pass. If c is shorter, reading c[i + j − 1] runs past its end and crashes, or a loop that stops at the end of c reports a merge that drops letters. An interleaving uses every letter of both strings exactly once, so the lengths must add up, and checking that costs O(1). For a = PQR and b = XY, the broadcast PXQY has 4 letters instead of 5, so the answer is false at once.

    From the lesson Interleavings and distinct subsequences

  11. Fresher to mid

    What are the two ways to rebuild the solution behind a DP's best value, and what does each cost?

    One way stores a choice for every state while the table is filled: the coin, item or move that produced its value. Rebuilding then follows the stored choices from the final state, one step per part of the answer and with no comparisons, at the price of a second array as large as the table. The other way keeps only the values and recomputes each choice during the walk: a transition belongs to an optimal answer exactly when it reproduces the stored value, as when best[a − c] equals best[a] − 1 for a coin c. That needs no extra memory and a few comparisons per step. Either way, choose the tie rule on purpose, because several transitions can reproduce the same value.

    From the lesson Rebuilding the answer from a DP table

Questions with model answers

What each question tests, the first step of a good answer and the follow-ups to expect.

  1. Mid to senior

    A cargo hold takes up to 10⁹ grams. There are 60 parcels, each weighing up to 10⁹ grams and worth between 1 and 1,000 points. Find the most valuable load. Which table do you fill, what does it cost, and what changes if the values can also reach 10⁹?

    What it tests
    Recognising when O(n·W) is impossible, switching the table to index by value, and knowing the next tool when both numbers are large.
    First step
    Price the usual table first: 60 × (10⁹ + 1) entries is far too many. Then look at the values: 60 parcels of at most 1,000 points add up to 60,000, so a row over values from 0 to 60,000, holding the lightest load that reaches each value, has only 60,001 entries.
    Follow-ups

    From the lesson 0/1 knapsack: table to one row

    Model answer, Pro. Model answers open with any pass; prices are in the notice on this page.

    Opening the model answers with your pass…

    Model answers open with any MySmartCoPilot pass.

    • Pro pass · 1 week₹79$2.99
    • 30 days₹179$5.99
    • 1 year₹1,699$45

    One payment; nothing renews unless you choose to. The price shown is the total you pay: no fees or charges are added at checkout.

    It also opens every other in-depth part in Learn and every Pro tool. Sales are final, except where the law gives you a right to withdraw, for example in the EU and the UK (refund policy).

    In the answer:

    • Model answer
    • Follow-up answers
    • Common mistakes
    • Rubric
    • Variants
    • about 3 minutes
  2. Mid to senior

    A drone carries at most 3 kg and 2 litres of cargo. Each of 50 packages has a weight in grams, a volume in millilitres and a delivery fee. Maximise the fees of one flight. How does the 0/1 knapsack table change, and how large does it get?

    What it tests
    Extending the state with a second capacity, keeping both loops downwards, and sizing the table before writing it.
    First step
    Add the second capacity to the state: best[w][v] is the most fee within w grams and v millilitres. Each package updates every pair (w, v) from high to low in both coordinates. Then size it: 3,001 × 2,001 pairs, about 6 million entries, updated by 50 packages, is 3 × 10⁸ steps.
    Follow-ups

    From the lesson 0/1 knapsack: table to one row

    Model answer, Pro.

    In the answer:

    • Model answer
    • Follow-up answers
    • Common mistakes
    • Rubric
    • Variants
    • about 3 minutes
  3. Mid to senior

    You must decide equal partitions for 200 numbers up to 1,000 in Python, with 2,000 test cases in one second. Compare a list of booleans with a Python integer used as a bitset: estimate both, and say when the bitset stops helping.

    What it tests
    Estimating Python-level work against work done inside the interpreter, knowing how big integers shift, and the limits of a bitset.
    First step
    Estimate the list first: about 200 × 50,000 = 10⁷ Python-level steps per case, so 2,000 cases are hopeless. Then count what the bitset does for one case: how many shifts and ORs, of how many bits, and where that work runs.
    Follow-ups

    From the lesson Subset sums, partitions and target signs

    Model answer, Pro.

    In the answer:

    • Model answer
    • Follow-up answers
    • Common mistakes
    • Rubric
    • Variants
    • about 3 minutes
  4. Fresher to mid

    Count the ways to put + or − before each of n numbers, some of them 0, so that the signed sum equals T. Derive the reduction to subset sums, and explain how zeros, an odd S + T and a target outside [−S, S] are handled.

    What it tests
    Deriving P = (S + T) / 2 from two equations, validating it before indexing, and seeing why every zero doubles the count.
    First step
    Name the totals: P for the numbers marked + and N for those marked −. Then P − N = T and P + N = S, so P = (S + T) / 2, and the sign choices are the subsets that add up to P. Before building any row, check that S + T is even and that |T| ≤ S.
    Follow-ups

    From the lesson Subset sums, partitions and target signs

    Model answer, Pro.

    In the answer:

    • Model answer
    • Follow-up answers
    • Common mistakes
    • Rubric
    • Variants
    • about 3 minutes
  5. Senior to staff

    Split 40 numbers, each up to 10¹², into two groups whose sums are as close as possible. A row over totals is impossible here. What do you do instead, and what does it cost?

    What it tests
    Seeing that a DP over totals fails when values are huge, and splitting the search into two halves combined with sorting and binary search.
    First step
    Size the row first: totals up to 4 × 10¹³ cannot be indexed. But the 2⁴⁰ subsets come from two halves of 20 numbers with 2²⁰, about a million, subsets each. List each half's subset sums, sort one list, and for each sum of the other half binary-search the partner that brings the total closest to S / 2.
    Follow-ups

    From the lesson Subset sums, partitions and target signs

    Model answer, Pro.

    In the answer:

    • Model answer
    • Follow-up answers
    • Common mistakes
    • Rubric
    • Variants
    • about 3 minutes
  6. Fresher to mid

    A colleague's code returns 9 for the number of ways to make 5 with coins 1, 2 and 5, but the expected answer is 4. Find the bug, explain what each loop order counts, and say how you would test the fix.

    What it tests
    Telling collections from ordered sequences, explaining why the order of the loops decides which one is counted, and testing against a brute force.
    First step
    List the 9 payments by hand and set them next to the 4 expected ones. Which of the 9 are the same collection of coins written differently? That tells you what the code counts. Then look at which of its two loops is the outer one.
    Follow-ups

    From the lesson Unbounded knapsack and coin change

    Model answer, Pro.

    In the answer:

    • Model answer
    • Follow-up answers
    • Common mistakes
    • Rubric
    • Variants
    • about 3 minutes
  7. Mid to senior

    A vending machine gives change with the fewest coins. It has 12 coin values, amounts go up to 10⁶ and it serves 10⁵ requests a day. Do you precompute or compute per request, how much memory does it take, and when could it safely pay the largest coin first?

    What it tests
    Trading precomputation against per-request cost, sizing tables in memory, and checking whether largest-first is safe for a coin system.
    First step
    Size both options. Precomputing fewest[a] and the last coin of each answer for amounts up to 10⁶ costs 12 × 10⁶ steps once and two arrays of 10⁶ 32-bit integers, about 8 MB; each request then lists its coins in as many steps as it returns coins. Computing per request would cost up to 12 × 10⁶ steps every time.
    Follow-ups

    From the lesson Unbounded knapsack and coin change

    Model answer, Pro.

    In the answer:

    • Model answer
    • Follow-up answers
    • Common mistakes
    • Rubric
    • Variants
    • about 3 minutes
  8. Senior to staff

    Count the ways to pay an amount A when coin value i has at most k_i copies, with 100 coin values, A up to 10⁵ and each k_i up to 10⁴. A loop over every copy is too slow. How do you count in O(A) time per coin value?

    What it tests
    Recognising the bounded knapsack, writing its sum as a sliding window over amounts with the same remainder, and keeping counts modulo a prime.
    First step
    Write the new count for one coin value c with k copies: new[a] = old[a] + old[a − c] + … + old[a − k·c]. Those terms all have the same remainder modulo c, so for each remainder the sum is a window of k + 1 entries that slides along the amounts r, r + c, r + 2c and so on.
    Follow-ups

    From the lesson Unbounded knapsack and coin change

    Model answer, Pro.

    In the answer:

    • Model answer
    • Follow-up answers
    • Common mistakes
    • Rubric
    • Variants
    • about 3 minutes
  9. Fresher to mid

    Count the routes from the top-left to the bottom-right of a 1,000 × 1,000 grid with closed cells, moving right or down, modulo 10⁹ + 7, in O(columns) memory. Then every route must pass a depot cell. How does the count change?

    What it tests
    Compressing a two-dimensional table to one row safely, and splitting a constrained count into a product of two independent counts.
    First step
    Write the two-dimensional rule first, then ask which entries one update reads: the cell above and the cell to the left. Which of the two does a single row still hold at the moment of the update, and in which order must a row be filled? For the depot, ask where every route must pass.
    Follow-ups

    From the lesson Grid DP: paths, costs and squares

    Model answer, Pro.

    In the answer:

    • Model answer
    • Follow-up answers
    • Common mistakes
    • Rubric
    • Variants
    • about 3 minutes
  10. Mid to senior

    Your maximal-square DP works on a 1,000 × 1,000 map. Now the interviewer asks for the largest all-ones rectangle. Why doesn't the three-neighbour rule extend to rectangles, and what do you use instead, at what cost?

    What it tests
    Seeing why a square is fixed by one number and a rectangle is not, and reducing the rectangle to the largest rectangle in a histogram, row by row.
    First step
    Try to extend the rule and look for a small counterexample: what does a rectangle ending at a cell need to know that a square does not? Then think of each row of the map as a floor, and of what stands on it in each column.
    Follow-ups

    From the lesson Grid DP: paths, costs and squares

    Model answer, Pro.

    In the answer:

    • Model answer
    • Follow-up answers
    • Common mistakes
    • Rubric
    • Variants
    • about 3 minutes
  11. Senior to staff

    Two couriers start together at the top-left of an n × n grid and each moves right or down to the bottom-right. Each cell holds parcels that are collected once, even if both couriers pass it. Maximise the parcels collected: give the state, the transitions and the cost for n = 200.

    What it tests
    Moving two walkers in lockstep to keep the state small, avoiding double counting, and sizing a cubic table.
    First step
    Start with why sending one courier and then the other can lose. Then look for a state that describes both couriers at once without four coordinates: what do their two positions have in common after the same number of moves?
    Follow-ups

    From the lesson Grid DP: paths, costs and squares

    Model answer, Pro.

    In the answer:

    • Model answer
    • Follow-up answers
    • Common mistakes
    • Rubric
    • Variants
    • about 2 minutes
  12. Mid to senior

    Two configuration files of 100,000 lines each differ in about 30 lines. Your diff fills the LCS table and runs out of memory. What do you change, and what does each option cost in time and memory?

    What it tests
    Sizing an O(nm) table, choosing a method whose cost grows with the number of differences, and knowing what linear-memory methods give and do not give.
    First step
    Size the table: about 100,001 × 100,001 cells, roughly 10¹⁰, which is 40 GB even at 4 bytes a cell, so no table of that shape can work. Then notice what is small, the 30 changed lines, and look for a method whose cost grows with the differences. Cut off the lines both files share at the start and the end first.
    Follow-ups

    From the lesson Longest common subsequence and diffs

    Model answer, Pro.

    In the answer:

    • Model answer
    • Follow-up answers
    • Common mistakes
    • Rubric
    • Variants
    • about 3 minutes
  13. Mid to senior

    Prove that when two strings end with the same character, some longest common subsequence ends with that character matched in both strings. Then explain why the LCS table never needs the maximum of three cells when the two characters are equal.

    What it tests
    An exchange argument on matched positions, the difference between some optimal solution and every one, and proving a recurrence instead of trusting it.
    First step
    Take any LCS S of a[:i] and b[:j] whose last characters are both x. Split into cases by whether S uses the last position of a, the last position of b, both or neither, and in each case build an LCS of the same length that uses both last positions.
    Follow-ups

    From the lesson Longest common subsequence and diffs

    Model answer, Pro.

    In the answer:

    • Model answer
    • Follow-up answers
    • Common mistakes
    • Rubric
    • Variants
    • about 3 minutes
  14. Senior to staff

    A code-review tool shows minimal line diffs, yet reviewers complain: closing braces and blank lines get matched across unrelated functions, and a moved function shows up as a large deletion and insertion. How would you make the diffs easier to read, and what do you give up?

    What it tests
    Seeing that minimal is not the same as readable, anchoring on rare lines, treating noise lines as junk, cleaning up the output, detecting moves, and stating the trade-offs.
    First step
    Reproduce it on a small case, such as two functions that end with the same closing lines, one of them edited. Count the changed lines of the minimal diff and of the diff a reviewer wants. The gap shows that the objective, the fewest changed lines, is the problem, not the algorithm that meets it.
    Follow-ups

    From the lesson Longest common subsequence and diffs

    Model answer, Pro.

    In the answer:

    • Model answer
    • Follow-up answers
    • Common mistakes
    • Rubric
    • Variants
    • about 3 minutes
  15. Senior to staff

    A delivery app must match a typed locality name against 1,000,000 official names in under 50 ms, allowing up to 2 typing slips. Comparing it with every name through the full table is far too slow. What do you build?

    What it tests
    Pricing the naive scan, pruning by length and with a band, choosing an index such as a trie walk, deletion neighbourhoods or a BK-tree, and measuring the result.
    First step
    Price the scan: a million names of about 12 letters at 144 cells each is about 1.4 × 10⁸ cell updates per query, far beyond 50 ms. Then use the limit of 2: a name whose length differs by more than 2 is out, and for the others a band of 5 diagonals is enough.
    Follow-ups

    From the lesson Edit distance with operations

    Model answer, Pro.

    In the answer:

    • Model answer
    • Follow-up answers
    • Common mistakes
    • Rubric
    • Variants
    • about 3 minutes
  16. Mid to senior

    Your function returns the edit operations, and a unit test compares them with a fixed list. After a refactor of the walk back the test fails, although the distance is unchanged and the new list is also correct. What happened, and how should the function and the tests change?

    What it tests
    Knowing that several optimal scripts exist, writing the tie rule into the contract, and testing properties instead of one arbitrary output.
    First step
    Run both versions on the failing input and apply each list of operations to the typed string. If both reach the target with the same number of edits, the refactor changed which optimal script the walk picks, not whether it is right. Then compare the order in which the two walks test the diagonal, the cell above and the cell to the left.
    Follow-ups

    From the lesson Edit distance with operations

    Model answer, Pro.

    In the answer:

    • Model answer
    • Follow-up answers
    • Common mistakes
    • Rubric
    • Variants
    • about 3 minutes
  17. Senior to staff

    A team counts a swap of two neighbouring letters as one edit and stores names in a BK-tree, which prunes its search with the triangle inequality. Some searches now miss names that are within the search radius. Explain why, and fix it.

    What it tests
    Knowing that the optimal string alignment distance is not a metric, how a BK-tree uses the triangle inequality, and the ways out.
    First step
    Find three strings for which the swap-aware distance breaks d(x, z) ≤ d(x, y) + d(y, z); small ones exist, such as ab, ba and bca. Then find the step of the BK-tree search that relies on that inequality to skip a whole subtree.
    Follow-ups

    From the lesson Edit distance with operations

    Model answer, Pro.

    In the answer:

    • Model answer
    • Follow-up answers
    • Common mistakes
    • Rubric
    • Variants
    • about 3 minutes
  18. Mid to senior

    A candidate computes the longest palindromic subsequence as the LCS of the string and its reverse, then prints that LCS as the palindrome. For ABCAB the program prints ACB. Is the length right? Why is the printed string wrong, and how do you print a real palindrome?

    What it tests
    Proving both directions of the LCS identity, seeing that an optimal LCS need not be a palindrome, and repairing the output.
    First step
    Check the easy direction first: any palindromic subsequence of s is also a subsequence of its reverse, so the LCS is at least as long. Then write the LCS as pairs of positions in s, one for its copy in s and one for its copy in the reverse, and look at how those pairs nest.
    Follow-ups

    From the lesson Palindromic substrings and subsequences

    Model answer, Pro.

    In the answer:

    • Model answer
    • Follow-up answers
    • Common mistakes
    • Rubric
    • Variants
    • about 2 minutes
  19. Senior to staff

    A label printer must turn product codes of up to 100,000 characters into palindromes with the fewest insertions. The interval table would need 10¹⁰ cells. Most codes are almost palindromes already. What do you compute, and what do you tell the product team about the worst case?

    What it tests
    Rewriting insertions as n minus the longest palindromic subsequence, using an algorithm whose cost grows with a small answer, and stating the quadratic worst case honestly.
    First step
    Write the answer k as n − LPS, and notice that the insert-and-delete distance between s and its reverse is exactly 2k. If codes are nearly palindromes, k is small, so a method whose cost grows with the distance applies: Myers' search on s and its reverse, or a band of width about 2k.
    Follow-ups

    From the lesson Palindromic substrings and subsequences

    Model answer, Pro.

    In the answer:

    • Model answer
    • Follow-up answers
    • Common mistakes
    • Rubric
    • Variants
    • about 2 minutes
  20. Mid to senior

    You count the palindromic subsequences of a 1,000-character string modulo 1,000,000,007 with the inclusion–exclusion table, in Java. Some answers come out negative. Why, how do you fix it, and what changes if the question asks for distinct palindromes?

    What it tests
    Subtraction under a modulus in typed languages, overflow bounds of the intermediate values, and the harder count of distinct palindromes.
    First step
    Look at the recurrence: the cell above plus the cell to the left, minus the cell between them. Once each cell is reduced modulo the prime, the subtracted value can be larger than the sum, and Java's remainder operator keeps the sign of a negative dividend.
    Follow-ups

    From the lesson Palindromic substrings and subsequences

    Model answer, Pro.

    In the answer:

    • Model answer
    • Follow-up answers
    • Common mistakes
    • Rubric
    • Variants
    • about 2 minutes
  21. Senior to staff

    A web service validates user input with a regular expression, and one request kept a CPU core busy for minutes. How do you confirm the cause, stop it now, and keep it from coming back?

    What it tests
    Recognising catastrophic backtracking, reproducing it with timings, immediate mitigations, and lasting fixes: safer patterns, possessive or atomic forms, linear-time engines and review rules.
    First step
    Reproduce it offline with the pattern and the input of the slow request, timing the match on prefixes of growing length. If each few extra characters multiply the time, the engine is exploring exponentially many ways to split the input, and the server is not simply slow.
    Follow-ups

    From the lesson Wildcard and regex-style matching

    Model answer, Pro.

    In the answer:

    • Model answer
    • Follow-up answers
    • Common mistakes
    • Rubric
    • Variants
    • about 3 minutes
  22. Senior to staff

    Prove that the greedy wildcard matcher, which on a mismatch backs up only to the most recent star, never misses a match. Then give its worst case, and say when you would still use the table.

    What it tests
    An exchange argument about stars and segments, a worst-case input with its cost, and the trade-off between O(1) memory and a guaranteed bound.
    First step
    Split the mask at its stars into segments without stars. Suppose some match places a segment later than the greedy matcher does. Show that moving it to the earliest place where it fits keeps the match valid, because the stars around it absorb whatever lies between.
    Follow-ups

    From the lesson Wildcard and regex-style matching

    Model answer, Pro.

    In the answer:

    • Model answer
    • Follow-up answers
    • Common mistakes
    • Rubric
    • Variants
    • about 3 minutes
  23. Senior to staff

    Extend the wildcard matcher to file paths: * and ? must not match a slash, and ** matches any number of whole directories, including none. How does the table change, and which edge cases need tests?

    What it tests
    Pinning down the semantics before coding, changing the transitions of a table for a richer grammar, and testing the cases around separators.
    First step
    Write the semantics down with examples first: does src//x.py match src/x.py, and may match part of a file name? Then give each piece its own rule: a single star may swallow one more character only if it is not a slash, while **/ covers nothing or a run that ends with a slash.
    Follow-ups

    From the lesson Wildcard and regex-style matching

    Model answer, Pro.

    In the answer:

    • Model answer
    • Follow-up answers
    • Common mistakes
    • Rubric
    • Variants
    • about 2 minutes
  24. Fresher to mid

    A colleague checks interleavings by taking each letter of c from a whenever a's next letter fits, and from b otherwise. It passes every sample test. Is it correct? Give the smallest counterexample, the fix and what the fix costs.

    What it tests
    Testing a greedy rule against a brute force, finding a smallest counterexample, and replacing the rule with the table at a known cost.
    First step
    Ask when the rule faces a real choice: both queues offer the same next letter. Build the smallest input where taking that letter from a leaves the following letter of c with no queue to come from, and confirm it with a brute force over every split.
    Follow-ups

    From the lesson Interleavings and distinct subsequences

    Model answer, Pro.

    In the answer:

    • Model answer
    • Follow-up answers
    • Common mistakes
    • Rubric
    • Variants
    • about 2 minutes
  25. Senior to staff

    An audit needs the exact number of ways a 40-character code occurs as a subsequence of a log of 100,000 characters, not a remainder. What do you store, what does it cost in time and memory, and how do you test it?

    What it tests
    Bounding the size of the answer, pricing big-integer additions and the memory of one row, and testing against exact formulas.
    First step
    Bound the answer first: at most comb(100,000, 40), a number of 153 digits, about 506 bits. So every count fits in eight 64-bit words, and the work is at most 40 additions of such numbers per log character.
    Follow-ups

    From the lesson Interleavings and distinct subsequences

    Model answer, Pro.

    In the answer:

    • Model answer
    • Follow-up answers
    • Common mistakes
    • Rubric
    • Variants
    • about 3 minutes
  26. Senior to staff

    Three services each emit an ordered stream of events, and a collector writes one merged log. How do you check that the log is a valid interleaving of the three streams, and how does the cost grow with the number of streams?

    What it tests
    Generalising the table to k sequences, noticing when identifiers make the problem linear, and choosing a check that works in production.
    First step
    Ask whether each event carries its source or a unique id. If it does, the question is only whether each stream's events appear in their order, which one pass with k pointers answers. The table, with one dimension per stream, comes back only when sources are unknown and events repeat.
    Follow-ups

    From the lesson Interleavings and distinct subsequences

    Model answer, Pro.

    In the answer:

    • Model answer
    • Follow-up answers
    • Common mistakes
    • Rubric
    • Variants
    • about 3 minutes
  27. Mid to senior

    Your coin-change function returns one list of coins on your laptop and a different list on the build server, and a snapshot test fails. Both lists are optimal. What is going on, and how do you fix both the code and the test?

    What it tests
    Finding the hidden sources of non-determinism in a reconstruction, writing a tie rule into the specification, and testing properties instead of incidental output.
    First step
    Compare the inputs as the function receives them: are the coins in the same order on both machines? If they come from a set, a dictionary or a query without ORDER BY, the order can differ, and a walk that takes the first coin that works then picks different, equally short lists.
    Follow-ups

    From the lesson Rebuilding the answer from a DP table

    Model answer, Pro.

    In the answer:

    • Model answer
    • Follow-up answers
    • Common mistakes
    • Rubric
    • Variants
    • about 3 minutes
  28. Senior to staff

    Prove that taking, at each step, the smallest coin c with best[a − c] = best[a] − 1 yields the first of the shortest coin lists in dictionary order. Would the same rule give the smallest edit script if you walked back from the end of the prefix table?

    What it tests
    An exchange argument for a tie rule, and how the direction of a walk decides which dictionary order it minimises.
    First step
    Call m the smallest coin that appears in any shortest list for a, and show that it passes the check: removing it leaves a list for a − m with one coin fewer. Then show that the walk's first coin is exactly m, and that no later coin can be smaller.
    Follow-ups

    From the lesson Rebuilding the answer from a DP table

    Model answer, Pro.

    In the answer:

    • Model answer
    • Follow-up answers
    • Common mistakes
    • Rubric
    • Variants
    • about 3 minutes
  29. Senior to staff

    A travel API finds the cheapest itineraries with a DP over flight legs, and the product wants every cheapest itinerary returned. Some queries have millions of ties. How do you design the response and the computation?

    What it tests
    Counting before listing, a deterministic order, paging by rank, limits on the response, and reporting totals honestly.
    First step
    Find out how many there are before producing any: a second table counts the cheapest itineraries of every state by adding up the counts of the transitions that keep the cost optimal. The count decides between returning everything, a page or a summary.
    Follow-ups

    From the lesson Rebuilding the answer from a DP table

    Model answer, Pro.

    In the answer:

    • Model answer
    • Follow-up answers
    • Common mistakes
    • Rubric
    • Variants
    • about 3 minutes

All Coding Interview Patterns interview questions · The Coding Interview Patterns track

Quick answers and tool search

Type to search tools or to get a quick answer, for example 18% of 2500. Use the up and down arrow keys to move through the results, Enter to choose, and Escape to close.