Problem 97

Abstract / Summary

Given three strings, determine if the third string can be formed by interleaving the characters of the first two strings in order.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0097.py

class Solution:
    def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
        if len(s1) + len(s2) != len(s3):
            return False

        LAST = "|"
        s1 += LAST
        s2 += LAST

        @cache
        def deeper(a, b):
            c = a + b
            if c == len(s3):
                return True

            if s3[c] == s1[a] and s3[c] == s2[b]:
                return deeper(a+1, b) or deeper(a, b+1)
            if s3[c] == s1[a]:
                return deeper(a+1, b)
            if s3[c] == s2[b]:
                return deeper(a, b+1)
            return False

        return deeper(0, 0)
24 lines | 647 bytes | submitted September 1, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 44% (1+ million submissions).

Typical patterns to solve this problem:
  • Dynamic Programming
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a method that determines whether a target string can be formed by interleaving two source strings while preserving the relative order of characters from each source. The algorithm first validates the basic length requirement, then augments the source strings with a sentinel character to simplify boundary handling. A depth-first search with memoization explores all feasible ways to consume characters from the two sources, returning true as soon as a complete match is found.

Key Steps

The first logical step checks that the combined length of the two source strings equals the length of the target. This guards against impossible cases early in the execution flow.

if len(s1) + len(s2) != len(s3):
    return False

Next, a sentinel character ("|") is appended to each source string. By placing a unique marker beyond the normal alphabet, the algorithm can safely reference the next character even when the index reaches the original end of a string.

LAST = "|"
s1 += LAST
s2 += LAST

The core of the solution is a nested recursive function named deeper. It is decorated with @cache, which automatically memoizes results for each pair of indices, preventing repeated work for identical sub-problems.

@cache
def deeper(a, b):
    c = a + b
    if c == len(s3):
        return True
    ...

Inside deeper, the variable c represents the current position in the target string, derived from the sum of characters already taken from both sources. When c reaches the length of the target, the recursion has successfully consumed the entire string, and the function returns True.

The matching logic proceeds by comparing the current target character with the characters at the current indices of the two source strings. If the target character matches both sources, the recursion branches, trying both possibilities. If it matches only one source, the recursion follows that single path. If there is no match, the function returns False.

if s3[c] == s1[a] and s3[c] == s2[b]:
    return deeper(a+1, b) or deeper(a, b+1)
if s3[c] == s1[a]:
    return deeper(a+1, b)
if s3[c] == s2[b]:
    return deeper(a, b+1)
return False

Finally, the outer method initiates the search from the start of both source strings.

return deeper(0, 0)

Edge Cases Handled

When the lengths of the inputs do not satisfy the necessary condition, the method exits immediately, handling mismatched length scenarios without further computation.

Appending the sentinel character ensures that attempts to access s1[a] or s2[b] after the original strings have been exhausted do not raise an index error. The sentinel is distinct from any valid input character, so it never falsely satisfies a match condition.

If both source strings are empty, the length check passes only when the target is also empty, leading the recursion to hit the base case (c == len(s3)) instantly and return True.

When the target character matches both sources simultaneously, the algorithm explores both continuation paths, guaranteeing that any valid interleaving that diverges at that point will be discovered.

Performance Optimizations

Memoization via the @cache decorator eliminates redundant exploration of identical index pairs. Each unique combination of positions in the two source strings is evaluated at most once, converting the exponential branching of a naïve depth-first search into a bounded number of sub-problem evaluations.

The sentinel technique removes the need for explicit boundary checks before each character comparison, allowing the core matching logic to remain concise and avoiding extra conditional branches that could degrade execution speed.

Early termination is built into the recursion: as soon as a complete match is found (c == len(s3)), the function returns True without further descent, preventing unnecessary work after a successful path has been identified.

Overall, the combination of length pre-validation, sentinel usage, and cached recursion yields an implementation that explores the solution space efficiently while maintaining clear and straightforward control flow.

written by openai gpt

ELI5 - Simplified Explanation

Imagine having two stacks of colorful building blocks named s1 and s2. Both stacks have special letters written on them. There is also a third stack called s3 that has a mix of letters from the first two. The goal is to see if s3 was made by taking blocks from the first two stacks one by one without ever changing the order the letters appeared in their original piles.

The code first checks if the number of blocks in the first two piles adds up to the number of blocks in the final pile. If the total number of blocks does not match, then it is impossible to make s3, so the process stops right away.

To help keep track of where the letters are, the code adds a secret marker to the end of the first two piles. Think of this marker like a little sign that says the pile is finished.

The computer then starts a game called deeper. This game looks at the first letter of the third pile and asks if it came from the first pile or the second pile. If the letter is found at the top of either pile, the computer remembers that spot and moves to the next letter in the pile it chose. It keeps doing this, jumping back and forth between the two piles to match every single letter in s3. If the computer reaches the end of the third pile successfully, it means everything fits perfectly. The computer is very smart because it uses a memory trick called cache, which helps it remember paths it has already checked so it does not have to do the same work twice.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 6.67 | σ = 1.19

Complexity Analysis

Time: polynomial
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java C# Rust Go TS
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows Python
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
everthis JS
FelixFan1122 C#
fpdjsns C++
gaosq0604 Python
Garvit244 Python
gouthampradhan Java
halfrost Go
haoel C++
JoshCrozier JS
keineahnung2345 C++
linouk23 C++
lkwq007 Python
MacJim C++
martianoff Scala
qiyuangong Python
ruoru Rust
suxrobGM C#
varunu28 Java
vthwang Java
wisdompeak C++
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, C#, Go, Java, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows Python, Python
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
everthis JavaScript
FelixFan1122 C#
fpdjsns C++
gaosq0604 Python
Garvit244 Python
gouthampradhan Java
halfrost Go
haoel C++
JoshCrozier JavaScript
keineahnung2345 C++
linouk23 C++
lkwq007 Python
MacJim C++
martianoff Scala
qiyuangong Python
ruoru Rust
suxrobGM C#
varunu28 Java
vthwang Java
wisdompeak C++
zfang399 C++
50 links | 34 authors | 10 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Interleaving String | Dynamic Programming | Leetcode #97'
Techdose 31 mins
Interleaving String | Dynamic Programming | Leetcode #97
YouTube video 'Interleaving String | Leetcode 97 | Dynamic Programming'
Ayushi Sharma 14 mins
Interleaving String | Leetcode 97 | Dynamic Programming
YouTube video 'Cracking LeetCode 97. Interleaving String Problem | 1D Dynamic Programming | Optimize Your Code'
vanAmsen 13 mins
Cracking LeetCode 97. Interleaving String Problem | 1D Dynamic Programming | Optimize Your Code
YouTube video 'Interleaving String | Leetcode 97 | Live coding session | DP'
Coding Decoded 22 mins
Interleaving String | Leetcode 97 | Live coding session | DP
YouTube video '[Java] Leetcode 97. Interleaving String [DP Subsequence #6]'
Eric Programming 30 mins
[Java] Leetcode 97. Interleaving String [DP Subsequence #6]
YouTube video '97. Interleaving String (Leetcode Hard)'
Programming Live with Larry 22 mins
97. Interleaving String (Leetcode Hard)
YouTube video '97. Interleaving String | Leetcode | Medium | Java | Dynamic Programming | Google'
AlgorithmHQ 10 mins
97. Interleaving String | Leetcode | Medium | Java | Dynamic Programming | Google
YouTube video 'LeetCode 97.  Interleaving String | Dynamic Programming | Coding Walk-through | Interview Prep  🔥'
Cherry Coding [IIT-G] 13 mins
LeetCode 97. Interleaving String | Dynamic Programming | Coding Walk-through | Interview Prep 🔥
YouTube video 'Interleaving String | LeetCode 97 | Coders Camp'
Coders Camp 18 mins
Interleaving String | LeetCode 97 | Coders Camp
YouTube video '97. Interleaving String | LEETCODE MEDIUM | DYNAMIC PROGRAMMING | CODE EXPLAINER'
code Explainer 11 mins
97. Interleaving String | LEETCODE MEDIUM | DYNAMIC PROGRAMMING | CODE EXPLAINER
YouTube video 'Daily Leetcode #1242: Aug 25, 2023 - 97. Interleaving String'
Programming Live with Larry 10 mins
Daily Leetcode #1242: Aug 25, 2023 - 97. Interleaving String
YouTube video 'LeetCode 97. Interleaving String'
Happy Coding 14 mins
LeetCode 97. Interleaving String
YouTube video 'Daily Leetcode #828: Jul 07, 2022 - 97. Interleaving String'
Programming Live with Larry 16 mins
Daily Leetcode #828: Jul 07, 2022 - 97. Interleaving String
YouTube video 'Interleaving String | Recursion | Dynamic Programming | LeetCode 97 | Learn Overflow'
Learn Overflow 19 mins
Interleaving String | Recursion | Dynamic Programming | LeetCode 97 | Learn Overflow
YouTube video 'Daily Leetcode #428: Jun 02, 2021 - 97. Interleaving String'
Programming Live with Larry 19 mins
Daily Leetcode #428: Jun 02, 2021 - 97. Interleaving String
YouTube video '97. Interleaving String | Daily Leetcode Challenge | August | C++ | Java'
Mayur Programming Club 32 mins
97. Interleaving String | Daily Leetcode Challenge | August | C++ | Java
YouTube video 'LeetCode 97: Interleaving String | Java Solution | Dynamic Programming'
Code Scribbler 9 mins
LeetCode 97: Interleaving String | Java Solution | Dynamic Programming
YouTube video 'Interleaving String - LeetCode 97 - Python - Dynamic Programming'
Alpha-Code 29 mins
Interleaving String - LeetCode 97 - Python - Dynamic Programming
YouTube video 'Interleaving String - LeetCode #97 - C++'
Sean Chuah 14 mins
Interleaving String - LeetCode #97 - C++
YouTube video 'LeetCode 97: Interleaving String | CSharp Solution | Dynamic Programming'
Code Scribbler 9 mins
LeetCode 97: Interleaving String | CSharp Solution | Dynamic Programming
20 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

30 solutions   September 1, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality