Python 0010.py
class Solution:
@cache
def dot(self, text, pattern):
if not pattern:
return len(text) == 1
if pattern[0] == "*":
for i in range(len(text), -1, -1): # longest first
if self.match(text[i:], pattern[1:]):
return True
return False
if not text:
return False
return self.match(text[1:], pattern)
@cache
def star(self, text, pattern, letter):
same = 0
while same < len(text) and text[same] == letter:
same += 1
# longest first to reduce recursion
while same >= 0:
if self.match(text[same:], pattern):
return True
same -= 1
return False
@cache
def match(self, text, pattern):
if not pattern:
return not text
if pattern[0] == ".":
return self.dot(text, pattern[1:])
if len(pattern) >= 2 and pattern[1] == "*":
return self.star(text, pattern[2:], pattern[0])
if not text:
return False
i = 0
while i < len(pattern) and i < len(text) and pattern[i] == text[i]:
i += 1
if i > 0 and i < len(pattern) and pattern[i] == "*":
i -= 1
if i == 0:
return False
return self.match(text[i:], pattern[i:])
def isMatch(self, s: str, p: str) -> bool:
return self.match(s, p)
Difficulty
and has an acceptance rate of about 31% (4+ million submissions).
Typical patterns to solve this problem:
- Dynamic Programming
- 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 implementation provides a regular-expression matcher that supports the metacharacters “.” (any single character) and “*” (zero or more of the preceding element). The public entry point is isMatch, which forwards the problem to a recursive routine match. Three helper methods-dot, star, and match-are each memoized with @cache, allowing repeated sub-problems to be answered instantly. The design emphasizes early termination and a “longest-first” strategy to keep the recursion depth shallow.
Core Functions
dot
@cache
def dot(self, text, pattern):
if not pattern:
return len(text) == 1
if pattern[0] == "*":
for i in range(len(text), -1, -1): # longest first
if self.match(text[i:], pattern[1:]):
return True
return False
if not text:
return False
return self.match(text[1:], pattern)
dot handles the case where the current pattern character is “.”.
If the remaining pattern is empty, the function succeeds only when exactly one character remains in the input, reflecting the semantics of a solitary “.”.
When the next pattern token is “*”, the routine iterates from the full length of text down to zero, trying the longest possible consumption first. This ordering reduces the number of recursive calls because a successful match on a longer prefix eliminates the need to explore shorter prefixes.
If the input string is already exhausted, the function returns False because “.” cannot match an empty character. Otherwise it consumes one character from text and proceeds with the rest of the pattern.
star
@cache
def star(self, text, pattern, letter):
same = 0
while same < len(text) and text[same] == letter:
same += 1
# longest first to reduce recursion
while same >= 0:
if self.match(text[same:], pattern):
return True
same -= 1
return False
star implements the “X*” construct where letter is the character preceding the asterisk.
First it counts how many consecutive occurrences of letter appear at the start of text.
Then it attempts to match the remainder of the pattern after the asterisk against the suffix of text, again trying the longest possible run of letter first. By decreasing same only after a failed recursive call, the method avoids unnecessary re-evaluation of shorter prefixes once a longer one succeeds.
match
@cache
def match(self, text, pattern):
if not pattern:
return not text
if pattern[0] == ".":
return self.dot(text, pattern[1:])
if len(pattern) >= 2 and pattern[1] == "*":
return self.star(text, pattern[2:], pattern[0])
if not text:
return False
i = 0
while i < len(pattern) and i < len(text) and pattern[i] == text[i]:
i += 1
if i > 0 and i < len(pattern) and pattern[i] == "*":
i -= 1
if i == 0:
return False
return self.match(text[i:], pattern[i:])
match is the central dispatcher.
When the pattern is empty, it succeeds only if the input string is also empty.
A leading “.” delegates to dot.
A leading character followed by “” delegates to star.
If the input string is empty while the pattern still contains characters (other than a possible “” construct), the function returns False.
The loop advances i while the characters at the same positions in text and pattern are identical. This fast-path handles literal runs without recursion.
If the loop stops just before a “*”, the index is stepped back one position so that the asterisk can be treated as applying to the preceding literal character.
When no progress is made (i == 0), the pattern cannot match the current text, and the function returns False.
Otherwise the function recurses on the remaining suffixes of both strings.
Public API
def isMatch(self, s: str, p: str) -> bool:
return self.match(s, p)
isMatch simply forwards the supplied string and pattern to the memoized match routine, exposing a clean interface.
Edge-Case Handling
The code explicitly checks for empty patterns and empty input strings at several points, ensuring correct behavior for cases such as an empty pattern matching only an empty string, a solitary “.” matching exactly one character, and “*” constructs correctly handling zero occurrences.
When a pattern begins with “*”, the dot method treats the asterisk as a quantifier for the preceding “.” and iterates over all possible split points, including the case where the asterisk consumes no characters (i == len(text)).
The star method’s initial counting loop stops as soon as a character differs from the target letter, guaranteeing that only contiguous runs are considered, which aligns with the semantics of the regular-expression star operator.
If the input string ends before the pattern, the early if not text: return False clause prevents attempts to access characters beyond the string’s length.
Performance Optimizations
Memoization via @cache is applied to every recursive entry point (dot, star, match). This eliminates redundant recomputation of identical sub-problems, turning exponential-time recursion into a polynomial-time solution for typical inputs.
Both dot and star adopt a “longest-first” iteration order. By trying the maximal possible consumption of characters before falling back to shorter prefixes, the algorithm often finds a successful match early and avoids deeper recursive exploration of many smaller branches.
The literal-run loop inside match consumes matching characters in a tight while-loop without invoking recursion, reducing overhead for contiguous literal segments.
The conditional adjustment if i > 0 and i < len(pattern) and pattern[i] == "*": i -= 1 ensures that the asterisk is correctly associated with its preceding character without extra recursive calls, streamlining the transition from literal matching to quantified matching.
Overall, the combination of memoization, strategic iteration order, and direct literal consumption yields a matcher that scales well for patterns containing many repeated quantifiers.
ELI5 - Simplified Explanation
Imagine a magical detective who is trying to figure out if a secret code matches a message. The code starts with a big box called match that looks at the message letter by letter. If the detective sees a dot, it acts like a wild card that can pretend to be any single letter. The detective uses a special helper called dot to test out all the possibilities for that mysterious spot.
When the detective encounters a star symbol in the code, it means the letter before it can vanish or repeat as many times as it wants. The star helper rolls up its sleeves and tries every version of the message, from using no letters at all to using a whole bunch of them, to see if anything fits perfectly.
The match function acts like the leader of the team. It compares the beginning of the secret code with the message. If the letters match, it just moves forward to check the rest. If there is a dot or a star, it asks the helpers to do the tricky work. All of these helpers keep notes on what they have already tried so they do not have to do the same hard work twice. This helps the detective solve the puzzle as fast as possible until every letter is checked and everything is in the right place.
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 | C# | Rust | JS | Java | C | Go | PHP | ||||
| 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 | ||||||||||||
| fartem | Ruby | ||||||||||||
| FelixFan1122 | C# | ||||||||||||
| fengvyi | C++ | ||||||||||||
| fpdjsns | C++ | ||||||||||||
| gaosq0604 | Python | ||||||||||||
| Garvit244 | Python | ||||||||||||
| gouthampradhan | Java | ||||||||||||
| haoel | C++ | ||||||||||||
| JoshCrozier | JS | ||||||||||||
| keineahnung2345 | C++ | ||||||||||||
| linouk23 | C++ | ||||||||||||
| luangong | C++ | ||||||||||||
| lzl124631x | C++ | ||||||||||||
| MacJim | C++ | ||||||||||||
| qiyuangong | Python | ||||||||||||
| ruoru | Rust | ||||||||||||
| Shamik07 | Dart | ||||||||||||
| shreymehul | C# | ||||||||||||
| sonugiri1043 | C++ | ||||||||||||
| suxrobGM | C# | ||||||||||||
| vli02 | C | ||||||||||||
| wisdompeak | C++ | ||||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||||
| WalkCCC | C++, Python, Java | ||||||||||||
| leetcode.ca | C, C++, C#, Go, Java, JavaScript, PHP, Python, Rust | ||||||||||||
| 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 | ||||||||||||
| fartem | Ruby | ||||||||||||
| FelixFan1122 | C# | ||||||||||||
| fengvyi | C++ | ||||||||||||
| fpdjsns | C++ | ||||||||||||
| gaosq0604 | Python | ||||||||||||
| Garvit244 | Python | ||||||||||||
| gouthampradhan | Java | ||||||||||||
| haoel | C++ | ||||||||||||
| JoshCrozier | JavaScript | ||||||||||||
| keineahnung2345 | C++ | ||||||||||||
| linouk23 | C++ | ||||||||||||
| luangong | C++ | ||||||||||||
| lzl124631x | C++ | ||||||||||||
| MacJim | C++ | ||||||||||||
| qiyuangong | Python | ||||||||||||
| ruoru | Rust | ||||||||||||
| Shamik07 | Dart | ||||||||||||
| shreymehul | C# | ||||||||||||
| sonugiri1043 | C++ | ||||||||||||
| suxrobGM | C# | ||||||||||||
| vli02 | C | ||||||||||||
| wisdompeak | C++ |
Videos
Similar Problems
- problem 44: Wildcard Matching
Solved On The Same Day
- problem 263: Ugly Number
- problem 461: Hamming Distance
- problem 133: Clone Graph
- problem 142: Linked List Cycle II
- problem 143: Reorder List
- problem 264: Ugly Number II
- problem 313: Super Ugly Number
- problem 454: 4Sum II
- problem 477: Total Hamming Distance
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