Regular Expression Matching
Master this topic with zero to advance depth.
Regular Expression Matching
The Matching Logic
Implement regular expression matching with support for '.' and '*'.
- '.' matches any single character.
- '*' matches zero or more of the preceding element.
The Star (*) Dilemma
The '' is the most complex part of this problem. When we encounter a '', we have two choices:
- Zero match: Skip the preceding element and the '*' (e.g.,
a*matches empty string). - One or more match: If the current character matches the preceding element, we consume one character of the string and stay at the same position in the pattern to potentially match more.
Implement regex matching with support for '.' and '*'. Includes visual state-space analysis.
Examples
Level I: Recursive Backtracking (Naive)
Intuition
Handle the base match, then branch for the '*' character.
For each call, check if the first character matches. If the second character of the pattern is '*', branch into 'skip' or 'consume' cases.
Detailed Dry Run
s="aa", p="a*"
| Step | s | p | First Match? | Action |
| :--- | :--- | :--- | :--- | :--- |
| 1 | "aa" | "a*" | YES | '*' detected, split |
| 2.1 | "aa" | "" | NO | Skip branch FAIL |
| 2.2 | "a" | "a*" | YES | Consume branch, recurse |
| 3.1 | "" | "a*" | YES | Consume branch, RES: true |Level II: Top-Down Memoization
Intuition
Cache results of (i, j) pairs where i is index in s and j is index in p.
The naive recursion has overlapping subproblems. By storing results in a 2D array/hashmap, we reduce complexity to .
Detailed Dry Run
Cache entries for s="aa", p="a*":
(0, 0) -> calls (0, 2) and (1, 0)
(0, 2) -> true (base case)
(1, 0) -> calls (1, 2) and (2, 0)
... all stored in memo table.Level III: Bottom-Up Dynamic Programming
Intuition
Build a table dp[i][j] where dp[i][j] is true if s[i:] matches p[j:].
Initialize dp[len(s)][len(p)] = true. Fill the table backwards from the base case.
Detailed Dry Run
DP Table for s="aa", p="a*":
| | a | * | (end) |
|---|---|---|-------|
| a | T | T | F |
| a | T | T | F |
|(e)| F | T | T |Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.