Problem 10

Abstract / Summary

Check if a text matches a pattern that can include dots and asterisks using regular expression rules.

Note

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

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)
57 lines | 1518 bytes | submitted August 19, 2023 | GitHub   4% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 31% (4+ million submissions).

Typical patterns to solve this problem:
  • Dynamic Programming
  • Recursion
  • 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 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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 28 | median = 4 | μ = 4.61 | σ = 1.86

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 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++
53 links | 35 authors | 12 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Regular Expression Matching - Dynamic Programming Top-Down Memoization - Leetcode 10'
NeetCode 28 mins
Regular Expression Matching - Dynamic Programming Top-Down Memoization - Leetcode 10
YouTube video 'Regular Expression Matching Dynamic Programming | Leetcode Hard Solutions'
Pepcoding 58 mins
Regular Expression Matching Dynamic Programming | Leetcode Hard Solutions
YouTube video 'Regular Expression Matching | Brute Force | Optimal | Recursion Concepts And Questions'
codestorywithMIK 55 mins
Regular Expression Matching | Brute Force | Optimal | Recursion Concepts And Questions
YouTube video 'LeetCode 10. Regular Expression Matching (Two Solutions: Recursion and DP)'
happygirlzt 22 mins
LeetCode 10. Regular Expression Matching (Two Solutions: Recursion and DP)
YouTube video 'Leetcode 10 Regular Expression Matching (Java) - Beats 100%'
TheAnalyticGuy 13 mins
Leetcode 10 Regular Expression Matching (Java) - Beats 100%
YouTube video 'DSA Phir se with Sumeet | Leetcode 10 | Regular Expression Matching'
Pepcoding 30 mins
DSA Phir se with Sumeet | Leetcode 10 | Regular Expression Matching
YouTube video 'Regular Expression Matching Python Solution - LeetCode #10'
Professor Oakes 8 mins
Regular Expression Matching Python Solution - LeetCode #10
YouTube video 'LeetCode - Regular Expression Matching (10)'
LeetCode Learning 18 mins
LeetCode - Regular Expression Matching (10)
YouTube video 'Leetcode 10. Regular Expression Matching Explanation + Coding (Java) #LeetCode #Java #Interview'
Algorithms Simplified 31 mins
Leetcode 10. Regular Expression Matching Explanation + Coding (Java) #LeetCode #Java #Interview
YouTube video 'Regular Expression Matching - 2 || DP 23 || Placement Preparation Series || Hard || LeetCode 10 ||'
Bro Coders 34 mins
Regular Expression Matching - 2 || DP 23 || Placement Preparation Series || Hard || LeetCode 10 ||
YouTube video '10. Regular Expression Matching (Leetcode Hard)'
Programming Live with Larry 28 mins
10. Regular Expression Matching (Leetcode Hard)
YouTube video 'LeetCode in C# | 10. Regular Expression Matching'
Josh Ackland 24 mins
LeetCode in C# | 10. Regular Expression Matching
YouTube video 'Regular Expression Matching - LeetCode #10 - C++'
Sean Chuah 13 mins
Regular Expression Matching - LeetCode #10 - C++
YouTube video '216. Leetcode 10. Regular Expression Matching : JAVA'
Web Fusion with Bharadwaj 14 mins
216. Leetcode 10. Regular Expression Matching : JAVA
YouTube video 'Leetcode 10: Regular Expression Matching in Telugu | DFS, Memoization, DP | Python DSA | srkcodes'
Srk Codes 15 mins
Leetcode 10: Regular Expression Matching in Telugu | DFS, Memoization, DP | Python DSA | srkcodes
YouTube video 'Leetcode Question 10 "Regular Expression Matching" in Javascript'
Ghumman Tech 6 mins
Leetcode Question 10 "Regular Expression Matching" in Javascript
YouTube video 'Apple Coding Interview Question | Leetcode 10 | Regular Expression Matching'
WorkWithGoogler 27 mins
Apple Coding Interview Question | Leetcode 10 | Regular Expression Matching
YouTube video 'LeetCode 10 | Regular Expression Matching | DP | Java'
Sleepy Cracker 14 mins
LeetCode 10 | Regular Expression Matching | DP | Java
YouTube video '121. Leetcode 10. Regular Expression Matching : Javascript'
Web Fusion with Bharadwaj 24 mins
121. Leetcode 10. Regular Expression Matching : Javascript
YouTube video 'ASMR Leetcode #10 : Regular Expression Matching Python solution'
ExtremeProgrammer 5 mins
ASMR Leetcode #10 : Regular Expression Matching Python solution
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

2 easy 7 medium
10 solutions   August 19, 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