Algo-Sim › Dynamic Programming

Interleaving String

Medium · Dynamic Programming · step through it in Java, Python and C++ on your own input

Is s3 a shuffle of s1 and s2 that keeps each one’s order? dp[i][j] asks it of the prefixes, one letter at a time.

Problem

Given strings s1, s2 and s3, return true if s3 is formed by interleaving s1 and s2: splitting both into pieces and merging the pieces so that the letters of each string keep their original order and every letter is used exactly once.

Constraints

Edge cases to test

Follow-up questions

Why is greedy wrong?
When both strings offer the same next letter, the right choice depends on later letters; the DP keeps both options.
How do you use O(n) space?
One row over s2’s prefixes, updated for each prefix of s1.

Solution

Java

public boolean isInterleave(String s1, String s2, String s3) {
    int m = s1.length(), n = s2.length();
    if (m + n != s3.length()) return false;
    boolean[][] dp = new boolean[m + 1][n + 1];
    dp[0][0] = true;
    for (int i = 0; i <= m; i++) {
        for (int j = 0; j <= n; j++) {
            if (i == 0 && j == 0) continue;
            char c = s3.charAt(i + j - 1);
            boolean fromS1 = i > 0 && dp[i - 1][j] && s1.charAt(i - 1) == c;
            boolean fromS2 = j > 0 && dp[i][j - 1] && s2.charAt(j - 1) == c;
            dp[i][j] = fromS1 || fromS2;
        }
    }
    return dp[m][n];
}

Python

def is_interleave(s1, s2, s3):
    m, n = len(s1), len(s2)
    if m + n != len(s3):
        return False
    dp = [[False] * (n + 1) for _ in range(m + 1)]
    dp[0][0] = True
    for i in range(m + 1):
        for j in range(n + 1):
            if i == 0 and j == 0:
                continue
            c = s3[i + j - 1]
            from_s1 = i > 0 and dp[i - 1][j] and s1[i - 1] == c
            from_s2 = j > 0 and dp[i][j - 1] and s2[j - 1] == c
            dp[i][j] = from_s1 or from_s2
    return dp[m][n]

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    bool isInterleave(string &s1, string &s2, string &s3) {
        int m = int(s1.size()), n = int(s2.size());
        if (m + n != int(s3.size()))
            return false;
        vector<vector<bool>> dp = vector<vector<bool>>(m + 1, vector<bool>(n + 1));
        dp[0][0] = true;
        for (int i = 0; i <= m; i++) {
            for (int j = 0; j <= n; j++) {
                if (i == 0 && j == 0)
                    continue;
                char c = s3[i + j - 1];
                bool fromS1 = i > 0 && dp[i - 1][j] && s1[i - 1] == c;
                bool fromS2 = j > 0 && dp[i][j - 1] && s2[j - 1] == c;
                dp[i][j] = fromS1 || fromS2;
            }
        }
        return dp[m][n];
    }
};

More Dynamic Programming problems