Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #97: Interleaving String

In this guide, we solve Leetcode #97 Interleaving String in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

Given strings s1, s2, and s3, find whether s3 is formed by an interleaving of s1 and s2. An interleaving of two strings s and t is a configuration where s and t are divided into n and m substrings respectively, such that: s = s1 + s2 + ...

Quick Facts

  • Difficulty: Medium
  • Premium: No
  • Tags: String, Dynamic Programming

Intuition

The problem breaks into overlapping subproblems, so caching results prevents exponential repetition.

A carefully chosen DP state captures exactly what we need to build the final answer.

Approach

Define the DP state and recurrence, then compute states in the correct order.

Optionally compress space once the recurrence is clear.

Steps:

  • Choose a DP state definition.
  • Write the recurrence and base cases.
  • Compute states in the correct order.

Example

Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac" Output: true Explanation: One way to obtain s3 is: Split s1 into s1 = "aa" + "bc" + "c", and s2 into s2 = "dbbc" + "a". Interleaving the two splits, we get "aa" + "dbbc" + "bc" + "a" + "c" = "aadbbcbcac". Since s3 can be obtained by interleaving s1 and s2, we return true.

Python Solution

class Solution: def isInterleave(self, s1: str, s2: str, s3: str) -> bool: @cache def dfs(i: int, j: int) -> bool: if i >= m and j >= n: return True k = i + j if i < m and s1[i] == s3[k] and dfs(i + 1, j): return True if j < n and s2[j] == s3[k] and dfs(i, j + 1): return True return False m, n = len(s1), len(s2) if m + n != len(s3): return False return dfs(0, 0)

Complexity

The time complexity is O(m×n)O(m \times n)O(m×n), and the space complexity is O(m×n)O(m \times n)O(m×n). The space complexity is O(m×n)O(m \times n)O(m×n).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy