Wildcard Matching

Match s against pattern p with `?` and `*` wildcards — greedy two-pointer with backtrack on mismatch.

Hard
Time O(n + m) Space O(1)
LeetCode
4 min read
greedy two-pointers string

Problem#

Implement matching with ? (any single char) and * (any sequence including empty). Return true iff the entire s is matched by p.

Examples#

  • s = "aa", p = "*"true
  • s = "cb", p = "?a"false
  • s = "adceb", p = "*a*b"true

Constraints#

  • 0 <= n, m <= 2000.

Approach#

DPdp[i][j] = does s[0..i-1] match p[0..j-1]. O(n × m).
Greedy two-pointer with backtrack — O(n + m) average. Remember the last * and the position in s to backtrack to on mismatch.

Solution#

Wildcard Matching (greedy)
class Solution {
public:
bool isMatch(string s, string p) {
int i = 0, j = 0, starIdx = -1, sBack = 0;
while (i < (int)s.size()) {
if (j < (int)p.size() && (p[j] == '?' || p[j] == s[i])) {
++i; ++j;
} else if (j < (int)p.size() && p[j] == '*') {
starIdx = j; sBack = i; ++j;
} else if (starIdx != -1) {
j = starIdx + 1;
i = ++sBack;
} else {
return false;
}
}
while (j < (int)p.size() && p[j] == '*') ++j;
return j == (int)p.size();
}
};

Editorial#

The greedy backtracks only to the most recent * — it represents the “we can absorb more characters” decision. On mismatch, extend the absorption by one character (advance sBack and reset j to one past the star). Any trailing *s in p after s is consumed are free matches.

Complexity#

  • Time: O(n + m) average; O(n × m) worst.
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.