Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Dynamic programming

Two-sequence DP: a table of prefix pairs

Lesson · 9 min read · Dynamic programming · Pattern: two sequences

Problems about two strings use a table indexed by a prefix of each. The cell compares the last characters and reads up, left and diagonal.

The pattern

Common subsequences and edit distance both index states by a pair of prefix lengths (i, j) and decide by looking at the last characters. The same table answers a family of questions about two sequences: how many times one appears in the other, whether a third string interleaves them, whether a pattern with wildcards matches, the shortest string containing both.

Two-sequence DP

dp[i][j]

  1. for prefixes a[:i] and b[:j]: combine dp[i − 1][j − 1] (use both last characters), dp[i − 1][j] (drop a's), dp[i][j − 1] (drop b's),
  2. depending on whether a[i − 1] and b[j − 1] match.

boundary

  1. row 0 and column 0: one string empty.

Worked example: how often does "rabbit" appear in "rabbbit"?

Count the subsequences of s equal to t. If the last characters match, either use that character of s for the last character of t, or do not: dp[i − 1][j − 1] + dp[i − 1][j]; otherwise only the second. An empty t appears once.

Rows: prefixes of rabbbit. Columns: prefixes of rabbit.

  1. Step 1 / 8
    ∅rabbit∅1000000r1a1b1b1b1i1t1

    Base cases filled first.

  2. Step 2 / 8
    ∅rabbit∅1000000r1100000a1b1b1b1i1t1

    Row r filled.

  3. Step 3 / 8
    ∅rabbit∅1000000r1100000a1110000b1b1b1i1t1

    Row a filled.

  4. Step 4 / 8
    ∅rabbit∅1000000r1100000a1110000b1111000b1b1i1t1

    Row b filled.

  5. Step 5 / 8
    ∅rabbit∅1000000r1100000a1110000b1111000b1112100b1i1t1

    Row b filled.

  6. Step 6 / 8
    ∅rabbit∅1000000r1100000a1110000b1111000b1112100b1113300i1t1

    Row b filled.

  7. Step 7 / 8
    ∅rabbit∅1000000r1100000a1110000b1111000b1112100b1113300i1113330t1

    Row i filled.

  8. Step 8 / 8
    ∅rabbit∅1000000r1100000a1110000b1111000b1112100b1113300i1113330t1113333

    Row t filled. "rabbit" appears 3 times in "rabbbit": one for each b that is left out.

How to recognise it

  • Two strings or arrays, and a question about matching, aligning or combining them.
  • Lengths up to about 1,000 each: O(n · m) is expected.
TimeO(n · m)
SpaceO(m) with two rows

The problems in this module: