Regular Expression Matching
Expert Answer & Key Takeaways
A complete guide to understanding and implementing Backtracking.
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
Input: s = "aa", p = "a*"
Output: true
Input: s = "mississippi", p = "mis*is*p*."
Output: false
Approach 1
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.
⏱ O((S+P) * 2^{S+P/2})💾 O(S^2 + P^2)
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 |Approach 2
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 .
⏱ O(S * P)💾 O(S * P)
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.Approach 3
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.⏱ O(S * P)💾 O(S * P)
Detailed Dry Run
DP Table for s="aa", p="a*":
| | a | * | (end) |
|---|---|---|-------|
| a | T | T | F |
| a | T | T | F |
|(e)| F | T | T |Course4All Technical Board
Verified ExpertSenior Software Engineers & Algorithmic Experts
Our DSA content is authored and reviewed by engineers from top tech firms to ensure optimal time and space complexity analysis.
Pattern: 2026 Ready
Updated: Weekly
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.