KatInterview

97. Interleaving String

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks whether a string s3 can be formed by interleaving two other strings, s1 and s2. This means s3 must be composed entirely of characters from s1 and s2, and the relative order of characters within s1 and s2 must be preserved in s3. For instance, if s1="ab" and s2="cd", "acbd" is a valid interleaving, but "adbc" is not, because the order of 'a' and 'b' from s1 is not maintained.

Solution

Interleaving String in Python

class Solution:
    def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
        n1, n2, n3 = len(s1), len(s2), len(s3)

        # The total length must match.
        if n1 + n2 != n3:
            return False

        # Optimization: Ensure s2 is the shorter string to use less DP space.
        # This recursive call swaps the strings if s1 is shorter than s2.
        if n1 < n2:
            return self.isInterleave(s2, s1, s3)

        # dp[j] will store whether an interleaving is possible for
        # s1's prefix of length i and s2's prefix of length j.
        # We use a 1D array of size n2+1.
        dp = [False] * (n2 + 1)

        dp[0] = True  # Base case: two empty strings can form an empty string.

        # Initialize the first row of the conceptual 2D DP table.
        # This corresponds to interleaving s2 with an empty s1.
        for j in range(1, n2 + 1):
            dp[j] = dp[j - 1] and s2[j - 1] == s3[j - 1]

        # Fill the DP table row by row for each character of s1.
        for i in range(1, n1 + 1):
            # First element of the row corresponds to interleaving s1's prefix with an empty s2.
            dp[0] = dp[0] and s1[i - 1] == s3[i - 1]

            for j in range(1, n2 + 1):
                # The current dp[j] holds the value from the previous row (i-1, j).
                # The current dp[j-1] holds the value from the current row (i, j-1).
                dp[j] = (dp[j] and s1[i - 1] == s3[i + j - 1]) or \
                        (dp[j - 1] and s2[j - 1] == s3[i + j - 1])

        return dp[n2]

Interleaving String in Java

class Solution {
    public boolean isInterleave(String s1, String s2, String s3) {
        int n1 = s1.length();
        int n2 = s2.length();
        int n3 = s3.length();

        // The total length must match.
        if (n1 + n2 != n3) {
            return false;
        }

        // Optimization: Ensure s2 is the shorter string to use less DP space.
        // This recursive call swaps the strings if s1 is shorter than s2.
        if (n1 < n2) {
            return isInterleave(s2, s1, s3);
        }

        // dp[j] will store whether an interleaving is possible for
        // s1's prefix of length i and s2's prefix of length j.
        // We use a 1D array of size n2+1.
        boolean[] dp = new boolean[n2 + 1];

        dp[0] = true; // Base case: two empty strings can form an empty string.

        // Initialize the first row of the conceptual 2D DP table.
        // This corresponds to interleaving s2 with an empty s1.
        for (int j = 1; j <= n2; j++) {
            dp[j] = dp[j - 1] && s2.charAt(j - 1) == s3.charAt(j - 1);
        }

        // Fill the DP table row by row for each character of s1.
        for (int i = 1; i <= n1; i++) {
            // First element of the row corresponds to interleaving s1's prefix with an empty s2.
            dp[0] = dp[0] && s1.charAt(i - 1) == s3.charAt(i - 1);
            
            for (int j = 1; j <= n2; j++) {
                // The current dp[j] holds the value from the previous row (i-1, j).
                // The current dp[j-1] holds the value from the current row (i, j-1).
                dp[j] = (dp[j] && s1.charAt(i - 1) == s3.charAt(i + j - 1)) || 
                        (dp[j - 1] && s2.charAt(j - 1) == s3.charAt(i + j - 1));
            }
        }

        return dp[n2];
    }
}

Interleaving String in C++

class Solution {
public:
    bool isInterleave(string s1, string s2, string s3) {
        int n1 = s1.length();
        int n2 = s2.length();
        int n3 = s3.length();

        // The total length must match.
        if (n1 + n2 != n3) {
            return false;
        }

        // Optimization: Ensure s2 is the shorter string to use less DP space.
        // This recursive call swaps the strings if s1 is shorter than s2.
        if (n1 < n2) {
            return isInterleave(s2, s1, s3);
        }

        // dp[j] will store whether an interleaving is possible for
        // s1's prefix of length i and s2's prefix of length j.
        // We use a 1D array of size n2+1.
        std::vector<bool> dp(n2 + 1, false);

        dp[0] = true; // Base case: two empty strings can form an empty string.

        // Initialize the first row of the conceptual 2D DP table.
        // This corresponds to interleaving s2 with an empty s1.
        for (int j = 1; j <= n2; ++j) {
            dp[j] = dp[j-1] && s2[j-1] == s3[j-1];
        }

        // Fill the DP table row by row for each character of s1.
        for (int i = 1; i <= n1; ++i) {
            // First element of the row corresponds to interleaving s1's prefix with an empty s2.
            dp[0] = dp[0] && s1[i-1] == s3[i-1];

            for (int j = 1; j <= n2; ++j) {
                // The current dp[j] holds the value from the previous row (i-1, j).
                // The current dp[j-1] holds the value from the current row (i, j-1).
                dp[j] = (dp[j] && s1[i-1] == s3[i+j-1]) || 
                        (dp[j-1] && s2[j-1] == s3[i+j-1]);
            }
        }

        return dp[n2];
    }
};

Interleaving String in TypeScript

function isInterleave(s1: string, s2: string, s3: string): boolean {
    const n1 = s1.length;
    const n2 = s2.length;
    const n3 = s3.length;

    // The total length must match.
    if (n1 + n2 !== n3) {
        return false;
    }

    // Optimization: Ensure s2 is the shorter string to use less DP space.
    // This recursive call swaps the strings if s1 is shorter than s2.
    if (n1 < n2) {
        return isInterleave(s2, s1, s3);
    }

    // dp[j] will store whether an interleaving is possible for
    // s1's prefix of length i and s2's prefix of length j.
    // We use a 1D array of size n2+1.
    const dp: boolean[] = new Array(n2 + 1).fill(false);

    dp[0] = true; // Base case: two empty strings can form an empty string.

    // Initialize the first row of the conceptual 2D DP table.
    // This corresponds to interleaving s2 with an empty s1.
    for (let j = 1; j <= n2; j++) {
        dp[j] = dp[j - 1] && s2[j - 1] === s3[j - 1];
    }

    // Fill the DP table row by row for each character of s1.
    for (let i = 1; i <= n1; i++) {
        // First element of the row corresponds to interleaving s1's prefix with an empty s2.
        dp[0] = dp[0] && s1[i - 1] === s3[i - 1];

        for (let j = 1; j <= n2; j++) {
            // The current dp[j] holds the value from the previous row (i-1, j).
            // The current dp[j-1] holds the value from the current row (i, j-1).
            dp[j] = (dp[j] && s1[i - 1] === s3[i + j - 1]) || 
                    (dp[j - 1] && s2[j - 1] === s3[i + j - 1]);
        }
    }

    return dp[n2];
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.