Wildcard Matching solution explained
Wildcard Matching asks whether a pattern with '?' (exactly one character) and '*' (any sequence, including an empty one) matches a whole string. A table where ok[i][j] means "the first i text characters match the first j pattern characters" solves it in O(n × m): '*' is true if it takes nothing (left cell) or one more character (cell above), and other characters must match the diagonal. A greedy two-pointer version that remembers the last '*' and backtracks to it uses O(1) extra memory.
By Evin JohnPublished 7 min read
The problem, restated
A question mark in the pattern matches any single character. A star matches any sequence of characters, of any length, including zero. Every other pattern character matches only itself. Return true if the pattern covers the entire text. This is the matching rule file names follow on most command lines, which is a good way to explain it.
| Text | Pattern | Match? | Why |
|---|---|---|---|
| report.pdf | yes | '*' takes report | |
| codex | c*?x | yes | '*' takes od, '?' takes e |
| codex | c?x | no | '?' covers one character, three are left over |
| aab | *a? | yes | '*' takes a, then a and '?' take ab |
| abc | *?*?*?*? | no | four question marks need at least four characters |
How it differs from regular expression matching
In Regular Expression Matching, '*' repeats the character before it, so a* can only produce a's. Here '*' is its own token and can swallow anything. That makes the table simpler (no need to look one character ahead) and it opens a greedy solution, because any '*' can absorb whatever a previous '*' gave up. Interviewers sometimes ask both problems in a row to see whether you notice the difference.
Dynamic programming over prefixes
Let ok[i][j] be true when the first i text characters match the first j pattern characters. The empty prefixes match. With no text, a pattern prefix matches only if it is all stars. For a star at pattern position j, either it matches nothing, so ok[i][j - 1], or it matches the text character i as well as whatever it matched before, so ok[i - 1][j]. For '?' or a letter, the characters must fit and ok[i - 1][j - 1] must hold. The code keeps a single row and a saved diagonal.
def wildcard_dp(text, pattern):
"""ok[j] after row i: does text[:i] match pattern[:j]? O(n * m) time."""
m = len(pattern)
ok = [False] * (m + 1)
ok[0] = True
for j in range(1, m + 1): # empty text: only a run of '*'
ok[j] = ok[j - 1] and pattern[j - 1] == "*"
for ch in text:
prev_diag, ok[0] = ok[0], False
for j in range(1, m + 1):
above = ok[j]
p = pattern[j - 1]
if p == "*":
ok[j] = ok[j - 1] or above # '*' takes nothing, or one more char
else:
ok[j] = prev_diag and (p == "?" or p == ch)
prev_diag = above
return ok[m]Greedy with a bookmark at the last star
Walk the text and the pattern together. When characters fit, advance both. When the pattern shows a star, bookmark it and let it match nothing for now. On a mismatch, if a star was seen, go back: let that star take one more text character and retry the pattern from just after the star. If no star was seen, the match has failed. When the text runs out, only stars may remain in the pattern.
def wildcard_greedy(text, pattern):
"""Two indexes plus a bookmark at the last '*'. O(n * m) worst case, O(1) space."""
i = j = 0
star = -1 # index of the last '*' seen in pattern
resume = 0 # text index that '*' is currently matched up to
while i < len(text):
if j < len(pattern) and pattern[j] in ("?", text[i]):
i += 1
j += 1
elif j < len(pattern) and pattern[j] == "*":
star, resume = j, i # let '*' match nothing for now
j += 1
elif star != -1:
resume += 1 # let '*' swallow one more character
i, j = resume, star + 1
else:
return False
while j < len(pattern) and pattern[j] == "*":
j += 1
return j == len(pattern)#include <string>
bool wildcardMatch(const std::string& text, const std::string& pattern) {
std::size_t i = 0, j = 0, resume = 0;
std::size_t star = std::string::npos;
while (i < text.size()) {
if (j < pattern.size() && (pattern[j] == '?' || pattern[j] == text[i])) {
++i;
++j;
} else if (j < pattern.size() && pattern[j] == '*') {
star = j++;
resume = i;
} else if (star != std::string::npos) {
i = ++resume;
j = star + 1;
} else {
return false;
}
}
while (j < pattern.size() && pattern[j] == '*') ++j;
return j == pattern.size();
}Why only the last star? Suppose an earlier star could have taken more. Anything it would have taken can instead be taken by the later star, because both match any sequence, and the part of the pattern between them has already been matched once. So backtracking to the most recent star never misses a match. That argument is what interviewers want when they ask why the greedy is correct.
Tracing the greedy on codex and c*?x
| Step | i (text) | j (pattern) | Action |
|---|---|---|---|
| 1 | 0 (c) | 0 (c) | match, both advance |
| 2 | 1 (o) | 1 (*) | bookmark star at 1, resume = 1, j = 2 |
| 3 | 1 (o) | 2 (?) | '?' matches o, both advance |
| 4 | 2 (d) | 3 (x) | mismatch: star takes o, i = 2, j = 2 |
| 5 | 2 (d) | 2 (?) | '?' matches d, both advance |
| 6 | 3 (e) | 3 (x) | mismatch: star takes od, i = 3, j = 2 |
| 7 | 3 (e) | 2 (?) | '?' matches e, both advance |
| 8 | 4 (x) | 3 (x) | match, both advance; text done, pattern done: true |
Cost
| Approach | Time | Extra memory |
|---|---|---|
| Plain recursion trying every split at each star | Exponential | O(n + m) stack |
| DP over prefixes | O(n × m) | O(m) with one row |
| Greedy with last-star bookmark | O(n × m) worst case, usually close to linear | O(1) |
Edge cases
- Both empty: true.
- Empty text with a pattern of stars only: true; with any '?' or letter: false.
- Empty pattern with non-empty text: false.
- Several stars in a row behave like one; you can collapse them first, which also speeds up the DP.
- A pattern ending in a star matches any remaining text.
Where answers go wrong
- Applying the regex rule and tying '*' to the previous character.
- In the DP, forgetting the empty-text row, so a leading star fails on an empty string.
- In the greedy, backtracking to the first star instead of the most recent one.
- Forgetting to skip trailing stars after the text is used up.
- Returning true when the text is used up but pattern letters remain.
How to explain it out loud
Fictional example
- Candidate
- I will start with a table over prefixes. A star cell is true if the star takes nothing, the cell to the left, or one more character, the cell above. Anything else needs the diagonal plus a character match. That is O(n times m).
- Interviewer
- Can you do it without the table?
- Candidate
- Yes. I walk both strings, bookmark the last star, and on a mismatch I let that star take one more character and restart the pattern just after it.
- Candidate
- Only the last star matters, because anything an earlier star could take, the later star can take instead. Extra memory is constant; the worst case is still n times m, but typical inputs run close to linear.
Same idea, other problems
- Glob matching with character classes like [a-c]. Same structure; the character test becomes a set lookup.
- Does a word appear in a stream with wildcards? Combine this matcher with a trie when many patterns are involved.
- Count the ways a pattern can match. Replace the booleans in the table with counts.
Related walkthroughs
Regular Expression Matching covers the harder star that repeats one character. Burst Balloons is a different kind of DP, over intervals instead of prefixes. The coding problems hub lists every walkthrough.
Practicing the greedy argument with Natively
The correctness argument for the last-star greedy is short, and saying it smoothly takes practice. Natively can transcribe your practice explanation on your Mac or Windows computer, so you can check that you stated why only the most recent star matters. During study, you can screenshot a wildcard prompt and ask it to compare the DP and the greedy for that input. The page on the AI assistant for coding interviews has more.
Questions people ask
How do you solve Wildcard Matching?
Use a table where ok[i][j] means the first i text characters match the first j pattern characters. A '*' cell is true if the cell to the left or the cell above is true; other cells need the diagonal and a matching character.
Is there a greedy solution to Wildcard Matching?
Yes. Walk both strings, bookmark the most recent '*', and on a mismatch let that star take one more character and retry just after it. It uses O(1) extra memory.
Why does the greedy only backtrack to the last star?
Anything an earlier star could have taken can be taken by a later star instead, since both match any sequence, so the most recent star is enough.
What is the difference between wildcard and regex matching?
In wildcard matching '*' matches any sequence by itself; in regex matching '*' repeats the preceding character.
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.
