Regular Expression Matching
Decide whether an entire string matches a pattern containing . and *.
Intuition
Greedily consuming as many characters as possible for can prevent the remainder from matching. At each string and pattern position, the future depends only on those two indices, making it a two-dimensional dynamic-programming state. A following creates two choices: skip the repeated token or consume one matching character and keep the pattern position. Memoization explores both without repeating the same suffix work.
Whole-string matching with operators that can consume variable amounts usually requires DP over string and pattern positions. A postfix star naturally creates skip-versus-consume transitions.
Approach
Describe matching by two suffix indices
Let match(i, j) mean that s[i:] matches p[j:] completely. If the pattern is exhausted, success requires the string to be exhausted too.
Compute whether the current tokens agree
The first characters match only when i is in range and either the pattern character equals s[i] or is .. This guard prevents reading beyond the string.
Branch only when the pattern token has a star
If p[j + 1] is *, either skip the token-star pair with match(i, j + 2) or consume one matching character with match(i + 1, j). Without a star, both indices must advance together.
Solution
Common pitfalls
Treating star as an independent character
first = p[j] == '*'
if j + 1 < len(p) and p[j + 1] == '*':
Star modifies the preceding token rather than matching input itself.
Advancing past star after consuming once
match(i + 1, j + 2)
match(i + 1, j)
The same starred token may consume additional characters.
Accepting when only the string ends
if i == len(s):
return Trueif j == len(p):
return i == len(s)Remaining pattern literals may still make the match invalid.
Edge cases
a*The zero-occurrence branch skips the pair and reaches two exhausted suffixes.
.*The dot matches any current character and the star may repeatedly consume it.
The base case rejects the match because the pattern is not exhausted with the string.