Python 0044.py
class Solution:
def isMatch(self, s: str, p: str) -> bool:
@cache
def match(posS, posP):
if posS == len(s) and posP == len(p):
return True
if posP == len(p):
return False
# wildcards
if p[posP] == "?":
if posS == len(s):
return False
return match(posS + 1, posP + 1)
if p[posP] == "*":
for i in range(posS, len(s) + 1):
if match(i, posP + 1):
return True
return False
if posS == len(s):
return False
# same letters
if p[posP] == s[posS]:
return match(posS + 1, posP + 1)
return False
return match(0, 0)
Difficulty
and has an acceptance rate of about 33% (2+ million submissions).
Typical patterns to solve this problem:
- Dynamic Programming
- Greedy
- Recursion
- String
AI Disclaimer
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.
Code Walkthrough
Overview
The provided implementation solves the classic wildcard matching problem where the pattern may contain the special characters ? (matching any single character) and * (matching any sequence of characters, including the empty sequence). The solution is expressed as a recursive depth-first search that is memoized using Python’s functools.cache decorator. By caching intermediate results, the algorithm avoids recomputing the same sub-problems, which is essential for handling the exponential number of possibilities introduced by the * wildcard.
Core Logic
The entry point is the isMatch method, which defines an inner function match(posS, posP). This function receives the current indices in the input string s and the pattern p. The recursion proceeds by examining the character at p[posP] and deciding how to advance the indices.
@cache
def match(posS, posP):
if posS == len(s) and posP == len(p):
return True
if posP == len(p):
return False
The first two conditional blocks handle the termination conditions. When both indices have reached the ends of their respective sequences, a complete match is reported. If the pattern is exhausted while the string still has characters, the match fails.
Handling the ? Wildcard
When the current pattern character is ?, the algorithm checks that there is still a character left in the string to consume. If the string is already at its end, the match fails; otherwise both indices are advanced by one.
if p[posP] == "?":
if posS == len(s):
return False
return match(posS + 1, posP + 1)
Handling the * Wildcard
The * wildcard is the most complex case because it can represent any number of characters, from zero up to the remainder of the string. The implementation iterates over all possible split points, invoking match recursively for each candidate. The loop starts at the current string position and goes through len(s) + 1, thereby including the empty-match scenario.
if p[posP] == "*":
for i in range(posS, len(s) + 1):
if match(i, posP + 1):
return True
return False
Because match is cached, each distinct pair (i, posP + 1) is evaluated at most once, preventing the exponential blow-up that a naïve recursive solution would suffer.
Literal Character Comparison
If the pattern character is neither ? nor *, the algorithm treats it as a literal. It first ensures that the string has not been exhausted; if it has, the match fails. When both characters are present, a direct equality check determines whether to continue recursion.
if posS == len(s):
return False
if p[posP] == s[posS]:
return match(posS + 1, posP + 1)
return False
The final return False covers the case where the current characters differ, leading to an immediate mismatch.
Edge Cases Addressed
The code explicitly checks for several boundary conditions:
- Both the input string and the pattern being empty results in a successful match.
- An empty pattern with a non-empty string returns
Falsebecause there are no pattern characters left to consume the remaining string characters. - A
?at the end of the pattern correctly fails when the string is already exhausted, ensuring that?never matches an empty position. - The
*loop includeslen(s) + 1as the upper bound, which allows the wildcard to match zero characters (the case wherei == posS) as well as the entire remaining suffix of the string. - Literal character comparison is guarded by a check that the string index is still within bounds, preventing out-of-range errors.
Performance Optimizations
The most significant optimization is the use of the @cache decorator on the recursive match function. By storing the result of each (posS, posP) pair, the algorithm eliminates redundant work. For example, when processing a *, many different recursive paths may converge on the same subsequent state; caching ensures that the expensive sub-computation is performed only once.
Another subtle optimization is the early exit in the ? and literal branches. As soon as a mismatch is detected, the function returns without exploring further recursion, reducing the number of cache lookups.
The loop for the * wildcard is written to iterate from the current position to the end of the string, but because each recursive call is cached, the overall number of distinct calls remains bounded by the product of the lengths of s and p. This boundedness keeps the runtime practical even for patterns with multiple * characters.
Overall Flow
The isMatch method simply invokes match(0, 0), starting the recursion from the beginning of both the string and the pattern. The combination of explicit base cases, distinct handling for each wildcard type, and memoization yields a clear and efficient solution to the wildcard matching problem.
ELI5 - Simplified Explanation
Imagine a game where two trains are traveling on tracks. One train is carrying a message made of letters, and the other train is a magic pattern that decides what that message is allowed to look like. The goal is to see if the pattern matches the message exactly.
There is a special helper inside the code that keeps track of where each train is standing at any moment. It looks at the current train car and asks if it matches the pattern car.
If the pattern has a question mark, that acts like a magic portal that can step over exactly one letter in the message. If the pattern has a star, that star is very flexible and can stretch to cover any number of letters, or even no letters at all, until it finds a part that matches the rest of the pattern.
When the pattern finds an ordinary letter, it just checks to see if the message has the same letter in that spot. If the letters match, the helper moves both trains forward to check the next spot.
This happens over and over, jumping from car to car, until the trains reach the very end. If both trains finish at the same time and everything lined up perfectly along the way, then the pattern has successfully matched the message. The little memory tool helps out so that if the trains have already visited a certain spot, the computer remembers what happened before and does not have to do the work again.
Code Quality
Complexity Analysis
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
Other Solutions
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# | Go | PHP | TS | |||||
| LeetcodeHelp | C++ | Python | Java | |||||||||
| MemoryLimitExceeded | C++ | Python | ||||||||||
| Progiez | C++ | Python | Java | |||||||||
| github | aylei | Rust | ||||||||||
| begeekmyfriend | C | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | Python | |||||||||||
| charles-wangkai | Java | |||||||||||
| chenyanzhe | C++ | |||||||||||
| everthis | JS | |||||||||||
| FelixFan1122 | C# | |||||||||||
| fengvyi | C++ | |||||||||||
| gaosq0604 | Python | |||||||||||
| Garvit244 | Python | |||||||||||
| gouthampradhan | Java | |||||||||||
| haoel | C++ | |||||||||||
| JoshCrozier | JS | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| lennylxx | C | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| luangong | C++ | |||||||||||
| MacJim | C++ | |||||||||||
| martianoff | Scala | |||||||||||
| qiyuangong | Python | |||||||||||
| ruoru | Rust | |||||||||||
| sonugiri1043 | C++ | |||||||||||
| suxrobGM | C# | |||||||||||
| varunu28 | Java | |||||||||||
| vli02 | C | |||||||||||
| wisdompeak | C++ | |||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||||
| WalkCCC | C++, Python, Java | |||||||||||
| leetcode.ca | C++, C#, Go, Java, PHP, Python, TypeScript | |||||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||||
| MemoryLimitExceeded | Python, C++ | |||||||||||
| Progiez | C++, Java, Python | |||||||||||
| aylei | Rust | |||||||||||
| begeekmyfriend | C | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | Python, Python | |||||||||||
| charles-wangkai | Java | |||||||||||
| chenyanzhe | C++ | |||||||||||
| everthis | JavaScript | |||||||||||
| FelixFan1122 | C# | |||||||||||
| fengvyi | C++ | |||||||||||
| gaosq0604 | Python | |||||||||||
| Garvit244 | Python | |||||||||||
| gouthampradhan | Java | |||||||||||
| haoel | C++ | |||||||||||
| JoshCrozier | JavaScript | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| lennylxx | C | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| luangong | C++ | |||||||||||
| MacJim | C++ | |||||||||||
| martianoff | Scala | |||||||||||
| qiyuangong | Python | |||||||||||
| ruoru | Rust | |||||||||||
| sonugiri1043 | C++ | |||||||||||
| suxrobGM | C# | |||||||||||
| varunu28 | Java | |||||||||||
| vli02 | C | |||||||||||
| wisdompeak | C++ |
Videos
Similar Problems
- problem 10: Regular Expression Matching
Solved On The Same Day
- problem 110: Balanced Binary Tree
- problem 111: Minimum Depth of Binary Tree
- problem 118: Pascal's Triangle
- problem 119: Pascal's Triangle II
- problem 228: Summary Ranges
- problem 530: Minimum Absolute Difference in BST
- problem 82: Remove Duplicates from Sorted List II
- problem 102: Binary Tree Level Order Traversal
- problem 103: Binary Tree Zigzag Level Order Traversal
- problem 105: Construct Binary Tree from Preorder and Inorder Traversal
- problem 106: Construct Binary Tree from Inorder and Postorder Traversal
- problem 107: Binary Tree Level Order Traversal II
- problem 109: Convert Sorted List to Binary Search Tree
- problem 117: Populating Next Right Pointers in Each Node II
- problem 128: Longest Consecutive Sequence
- problem 138: Copy List with Random Pointer
- problem 150: Evaluate Reverse Polish Notation
- problem 155: Min Stack
- problem 209: Minimum Size Subarray Sum
- problem 274: H-Index
- problem 380: Insert Delete GetRandom O(1)
- problem 427: Construct Quad Tree
- problem 452: Minimum Number of Arrows to Burst Balloons
- problem 30: Substring with Concatenation of All Words
- problem 37: Sudoku Solver
- problem 1326: Minimum Number of Taps to Open to Water a Garden
Extra
- 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