Regular Expression Matching solution explained
Regular Expression Matching asks whether a pattern with '.' (any one character) and '*' (zero or more of the character before it) matches an entire string. Define match(i, j) as "does the text from i match the pattern from j": if the next pattern token is x*, either skip the token or, when x matches text[i], consume one character and stay on the token; otherwise the current characters must match and both move on. Memoize it or fill the table bottom-up for O(n × m) time.
By Evin JohnPublished 7 min read
The problem, restated
You get a text and a pattern. In the pattern, a letter matches itself, a dot matches any single character, and a star means the character just before it may repeat zero or more times. The star always follows a letter or a dot, never starts the pattern. Return true only if the pattern matches the whole text, not just a part of it.
| Text | Pattern | Match? | Why |
|---|---|---|---|
| aaab | a*b | yes | a* takes three a's, then b |
| aaab | a*.b | yes | a* takes two a's, the dot takes the third |
| ab | .*c | no | .* can take ab, but nothing is left for c |
| (empty) | x*y* | yes | both starred tokens take zero characters |
| bba | b*a*a | yes | a* must give back its a so the final a can match |
The last row is the reason this problem is hard. If a* grabs every a it can, the final a has nothing left. A correct solution must be ready to let a starred token take fewer characters than it could.
Top-down recursion with a cache
Look at the pattern one token at a time. A token is either a single character or a character followed by a star. For a starred token there are two choices: it matches nothing (skip two pattern positions), or it matches one more text character, if that character fits, and stays in place to match more. For a plain token, the text character must fit and both positions advance. The recursion ends when the pattern is used up: success only if the text is used up too.
from functools import lru_cache
def is_match_memo(text, pattern):
"""Top-down: does pattern[j:] match text[i:]?"""
@lru_cache(maxsize=None)
def match(i, j):
if j == len(pattern):
return i == len(text)
first = i < len(text) and pattern[j] in (text[i], ".")
if j + 1 < len(pattern) and pattern[j + 1] == "*":
# skip "x*" entirely, or use it for one character and stay on it
return match(i, j + 2) or (first and match(i + 1, j))
return first and match(i + 1, j + 1)
return match(0, 0)Without the cache, the two choices at every star make the recursion exponential on inputs like a long run of a's against a pattern of several a* tokens followed by a letter that is not there. With the cache, each (i, j) pair is answered once.
Bottom-up table
The same recurrence fills a table from the end of both strings backward. ok[i][j] answers "does text[i:] match pattern[j:]"; ok[n][m] is true because two empty suffixes match. Note that the row i = n is filled too: an empty text can still match a pattern suffix made only of starred tokens.
def is_match(text, pattern):
"""Bottom-up: ok[i][j] is True when text[i:] matches pattern[j:]."""
n, m = len(text), len(pattern)
ok = [[False] * (m + 1) for _ in range(n + 1)]
ok[n][m] = True
for i in range(n, -1, -1):
for j in range(m - 1, -1, -1):
first = i < n and pattern[j] in (text[i], ".")
if j + 1 < m and pattern[j + 1] == "*":
ok[i][j] = ok[i][j + 2] or (first and ok[i + 1][j])
else:
ok[i][j] = first and ok[i + 1][j + 1]
return ok[0][0]function isMatch(text, pattern) {
const n = text.length, m = pattern.length;
// ok[i][j]: does text.slice(i) match pattern.slice(j)?
const ok = Array.from({ length: n + 1 }, () => new Array(m + 1).fill(false));
ok[n][m] = true;
for (let i = n; i >= 0; i--) {
for (let j = m - 1; j >= 0; j--) {
const first = i < n && (pattern[j] === text[i] || pattern[j] === ".");
if (j + 1 < m && pattern[j + 1] === "*") {
ok[i][j] = ok[i][j + 2] || (first && ok[i + 1][j]);
} else {
ok[i][j] = first && ok[i + 1][j + 1];
}
}
}
return ok[0][0];
}A small table
| text suffix \ pattern suffix | b*a*a | *a*a | a*a | *a | a | (end) |
|---|---|---|---|---|---|---|
| bba | T | . | . | . | . | . |
| ba | T | . | . | . | . | . |
| a | T | . | T | . | T | . |
| (end) | . | . | . | . | . | T |
Columns that start with a star are never true on their own, because the star belongs to the token before it; the code never reads those cells for a decision. Read the a row: a*a matches a because a* can take nothing and the final a takes the a. That is the "give it back" case from the examples, handled without any backtracking code.
Cost
| Approach | Time | Extra memory |
|---|---|---|
| Plain recursion | Exponential in the worst case | O(n + m) stack |
| Recursion with cache | O(n × m) | O(n × m) cache + stack |
| Bottom-up table | O(n × m) | O(n × m), or O(m) with two rows |
Edge cases
- Both empty: true.
- Empty text, pattern of starred tokens only (such as a*.*): true.
- Empty pattern, non-empty text: false.
- A dot followed by a star matches any text at all, including an empty one.
- Text longer than the pattern can cover without stars: false, and the table finds that without special cases.
Where answers go wrong
- Matching '*' greedily and never giving characters back.
- Treating '*' as a wildcard for any sequence; that is a different problem, Wildcard Matching.
- Looking at pattern[j] alone instead of checking whether pattern[j + 1] is a star first.
- Forgetting the empty-text row, so patterns like a*b* fail on an empty string.
- Checking only a prefix match because the loop stops when the pattern ends.
- Calling the language's regex engine. It gives the right answer, but the interview is about building the matcher.
How to explain it out loud
Fictional example
- Candidate
- I will define match(i, j) as whether the text from i matches the pattern from j. The base case: if the pattern is finished, the text must be too.
- Candidate
- If the next pattern character is followed by a star, I have two options. Skip the pair entirely, or, if the character fits text[i], use it for that one character and keep j where it is so the star can match more.
- Interviewer
- Why not just take as many as possible?
- Candidate
- Because a later part of the pattern may need some of those characters, like b*a*a on bba. Trying both options handles that, and with a cache there are only n times m states.
Same idea, other problems
- Edit distance between two words. A two-index table where each cell chooses between insert, delete and replace.
- Is one string a subsequence of another, many times over? A two-index walk, often preprocessed for speed.
- Interleaving two strings into a third. A two-index table of booleans, filled the same way.
Related walkthroughs
Wildcard Matching is the sibling problem where '*' matches any sequence on its own, and it adds a greedy solution this problem does not allow. Longest Valid Parentheses is another string problem where the obvious technique fails. The coding problems hub has the rest.
Studying matching problems with Natively
Matching problems reward a clear definition of the state before any code. Run a mock session with Natively transcribing on your Mac or Windows computer, and check afterward whether you said what match(i, j) means and handled the empty-text row out loud. When a practice prompt confuses you, screenshot it and ask for the two choices at a star rather than a full answer. The AI assistant for coding interviews page explains how that works.
Questions people ask
How do you solve Regular Expression Matching?
Define match(i, j) for text from i and pattern from j. If the pattern token is x*, either skip it or, when x fits text[i], consume one character and stay on the token; otherwise the characters must fit and both advance. Memoize or fill a table.
Why does a greedy star fail?
A starred token that takes every character it can may leave nothing for the rest of the pattern, as with bba against b*a*a. The DP tries both choices.
What is the time complexity of regex matching with DP?
O(n × m) for text length n and pattern length m, with O(1) work per state.
How is this different from Wildcard Matching?
Here '*' repeats the character before it. In wildcard matching '*' stands alone and matches any sequence.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
