Interleaving String

Pattern: Strings DP

medium

can[i][j] says whether the first i + j characters of s3 interleave the first i of s1 and the first j of s2. The last character came from s1 (check can[i-1][j]) or from s2 (check can[i][j-1]).

The problem

Return whether s3 is formed by interleaving s1 and s2: all characters of both, each string's order kept.

Think first

  • What is the first length check?
  • Where could s3's last character come from?
  • What do i and j tell you?

Hints

    Brute force, and why it fails

    Try both choices at every character: 2ⁿ.

    The key insight

    The state (i, j) fixes the position in s3, so a 2D table covers every choice.

    Dry run

    s1 'aabcc', s2 'dbbca', s3 'aadbbcbcac'.

    Step 1 of 2

    The plan

    can[0][0] = true
    can[i][j] = (can[i-1][j] and s1[i-1] == s3[i+j-1]) or (can[i][j-1] and s2[j-1] == s3[i+j-1])
    

    Complexity

    Time
    O(m × n)
    Space
    O(n)

    One row.

    Edge cases

    • Lengths do not add up: false.
    • Empty strings.
    • Equal characters in both.
    I've built my logic, show the code

    Java

    class Solution {
        public boolean isInterleave(String s1, String s2, String s3) {
            int m = s1.length(), n = s2.length();
            if (m + n != s3.length()) return false;
            boolean[] ok = new boolean[n + 1];      // ok[j] in row i: s3's first i + j characters are s1[0..i) and s2[0..j) mixed
            for (int i = 0; i <= m; i++)
                for (int j = 0; j <= n; j++) {
                    if (i == 0 && j == 0) { ok[0] = true; continue; }
                    boolean fromS1 = i > 0 && ok[j] && s1.charAt(i - 1) == s3.charAt(i + j - 1);   // the last character came from s1
                    boolean fromS2 = j > 0 && ok[j - 1] && s2.charAt(j - 1) == s3.charAt(i + j - 1);   // or from s2
                    ok[j] = fromS1 || fromS2;
                }
            return ok[n];
        }
    }

    C++

    class Solution {
    public:
        bool isInterleave(string s1, string s2, string s3) {
            int m = static_cast<int>(s1.size()), n = static_cast<int>(s2.size());
            if (m + n != static_cast<int>(s3.size())) return false;
            vector<bool> ok(n + 1, false);          // row i: s3's first i + j characters are s1[0..i) and s2[0..j) mixed
            for (int i = 0; i <= m; i++)
                for (int j = 0; j <= n; j++) {
                    if (i == 0 && j == 0) { ok[0] = true; continue; }
                    bool fromS1 = i > 0 && ok[j] && s1[i - 1] == s3[i + j - 1];        // the last character came from s1
                    bool fromS2 = j > 0 && ok[j - 1] && s2[j - 1] == s3[i + j - 1];    // or from s2
                    ok[j] = fromS1 || fromS2;
                }
            return ok[n];
        }
    };

    Python

    class Solution:
        def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
            m, n = len(s1), len(s2)
            if m + n != len(s3):
                return False
            ok = [False] * (n + 1)                  # row i: s3's first i + j characters are s1[0..i) and s2[0..j) mixed
            for i in range(m + 1):
                for j in range(n + 1):
                    if i == j == 0:
                        ok[0] = True
                        continue
                    from_s1 = i > 0 and ok[j] and s1[i - 1] == s3[i + j - 1]       # the last character came from s1
                    from_s2 = j > 0 and ok[j - 1] and s2[j - 1] == s3[i + j - 1]   # or from s2
                    ok[j] = from_s1 or from_s2
            return ok[n]

    Common mistakes

    • Greedy choice when both strings match.
    • Missing the length check.

    Similar problems