Wildcard Matching
Master this topic with zero to advance depth.
Wildcard Matching
Matching Rules
- '?' matches any single character.
- '*' matches any sequence of characters (including empty sequence).
The Greedy '*' Logic
Unlike Regular Expression matching where a* depends on 'a', the Wildcard * is independent. It can match anything. This makes it a great candidate for greedy search or dynamic programming.
Implement wildcard pattern matching with support for '?' and '*'. Includes visual matching trace.
Examples
Level I: Recursive Backtracking (Naive)
Intuition
Traverse both strings. If we hit '?', match one. If we hit '*', try matching zero or more characters.
Standard recursion with branching on '*'. This is in the worst case (e.g., s="aaaaa", p="*a*a*a").
Detailed Dry Run
s="aa", p="*"
| Step | s | p | Action |
| :--- | :--- | :--- | :--- |
| 1 | "aa" | "*" | '*' detected, branch |
| 2.1 | "aa" | "" | FAIL (skip *) |
| 2.2 | "a" | "*" | RECURSE (consume 'a') |
| 3.1 | "a" | "" | FAIL (skip *) |
| 3.2 | "" | "*" | SUCCESS (consume 'a', match empty) |Level II: Top-Down Memoization
Intuition
Overlap in recursive branches for '*' leads to redundant work.
Store (i, j) match results to achieve complexity.
Detailed Dry Run
For s="abc", p="*c":
memo[0][0] calls memo[0][1] and memo[1][0].
memo[1][0] calls memo[1][1] and memo[2][0].
Redundant paths like (*, c) matching 'bc' are cached.Level III: Optimized Greedy Path (Pointers)
Intuition
Instead of a full DP table, we can track the last '*' position and backtrack only as much as needed.
When we hit '', record the current s and p indices. If we hit a mismatch later, reset p to right after '', and s to one char after the previous recorded s index.
Detailed Dry Run
s="adceb", p="*a*b"
1. p[0]='*', star_idx=0, s_tmp=0. p moves to 1.
2. s[0]='a', p[1]='a'. Match! i=1, j=2.
3. p[2]='*', star_idx=2, s_tmp=1. p moves to 3.
4. s[1]='d', p[3]='b'. Mismatch! Backtrack to star_idx=2, s_tmp=2.
5. Keep trying until s[4]='b', p[3]='b'. MATCH!Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.